问题
Given a string s 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.【左括号必须以正确的顺序闭合】
Example 1:
Input: s = “()”
Output: true
Example 2:
Input: s = “()[]{}”
Output: true
Example 3:
Input: s = “(]”
Output: false
Example 4:
Input: s = “([)]”
Output: false
Example 5:
Input: s = “{[]}”
Output: true
Constraints:
- 1 <= s.length <= 104
- s consists of parentheses only ‘()[]{}’.
二、解析
go 解法:
func isValid(s string) bool {
n := len(s)
if n % 2 == 1 {
return false
}
pairs := map[byte]byte{
')':'(',
'}':'{',
']':'[',
}
stack := []byte{}
for i:= 0;i < n;i++{
if pairs[s[i]] > 0 {
if len(stack) == 0 || stack[len(stack)-1] != pairs[s[i]] {
return false
} else {
stack = stack[:len(stack)-1]
}
} else {
stack = append(stack,s[i])
}
}
return len(stack) == 0
}