Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Example 4:
1 |
|
Example 5:
1 |
|
Related Topics:String
、Stack
解題邏輯與實作
這題是在驗證括號是否成對,看到這種題目第一反應就是用 Stack:
- 依序遍歷輸入字串
- 若為左括號,則 push 進入 stack
- 若為右括號,則
- 若 Stack 為空,則回傳 False
- 若 Stack 不為空,則取出 Stack 頂端元素,判斷是否成對,若不成對則回傳 False,反之繼續向下執行。
- 直到字串遍歷完畢,且 Stack 為空,則回傳 True,反之回傳 False。
1 |
|
依照題目的輸入限制,進一步優化與精簡程式碼:
1 |
|