Description
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.
1 2
| Input: "()" Output: true
|
1 2
| Input: "()[]{}" Output: true
|
1 2
| Input: "(]" Output: false
|
1 2
| Input: "([)]" Output: false
|
1 2
| Input: "{[]}" Output: true
|
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| func isValid(s string) bool { stack := []string{}
pairs := map[string]string{ ")": "(", "]": "[", "}": "{", }
for i := 0; i < len(s); i++ { char := s[i : i+1]
if opposite, ok := pairs[char]; ok { if len(stack) == 0 || stack[len(stack)-1] != opposite { return false }
stack = stack[:len(stack)-1]
continue }
stack = append(stack, char) }
return len(stack) == 0 }
|
Note
假設有以下參數:
說明:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| 第 1 個符號為左括號,所以推進至堆疊中:
---------- { ----------
第 2 個符號為左括號,所以推進至堆疊中:
---------- {[ ----------
第 3 個符號為右括號,與最上層的元素配對成功,因此移出最上層的元素:
---------- { ----------
第 4 個符號為右括號,與最上層的元素配對成功,因此移出最上層的元素:
----------
----------
最終返回:true
|
Code