Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules:
- Any left parenthesis '(' must have a corresponding right parenthesis ')'.
- Any right parenthesis ')' must have a corresponding left parenthesis '('.
- Left parenthesis '(' must go before the corresponding right parenthesis ')'.
- '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string.
- An empty string is also valid.
Note:
The string size will be in the range [1, 100].
給予一個字串只包含三種字元:
(
、)
和*
,寫一個function去檢查這個字串是否合法。我們根據以下規則去定義字串是否合法:
- 一個左括號
(
必須對應到一個右括號)
。- 一個右括號
)
必須對應到一個左括號(
。- 左括號
(
必須在對應的右括號)
之前出現。*
可以當作是一個右括號)
或是一個左括號(
或是空的字串。- 空字串也是合法的。
注意:
字串大小在1到100之間。
*
)。(
和*
的時候放入堆疊,而遇到)
時去檢查堆疊。)
,不合法。(
也有*
在堆疊中,優先拿出(
。*
當作(
的部分。接著要檢查堆疊剩下來的東西是否合法。*
在這個階段只會變成)
或是空字串,那麼我們可以想成所有的*
都是)
,但是有剩下來的也無妨。
((***
,改為(()))
去想,並且多餘的)
也當作合法就好了!**(
就會變成))(
,這樣就不合法。string
當作堆疊,並且用了rfind()
和replace()
等等的炫技。
(
並移除而已,不用太緊張XD(
和*
的個數,就沒有再換成)
之類的了。(上面只是方便理解,實務上那樣做沒有什麼意義而且會變慢)LeetCode
C++