LeetCode-0020-Valid Parentheses
题目
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
func isValid(s string) bool { //这个解法用到了acsii值
if len(s) == 0 {
return true
}
left := make([]int, 1)
left[0] = int(s[0])
for i := 1; i < len(s); i++ {
a := int(s[i])
if len(left) == 0 {
left = append(left, a)
continue
}
if a-left[len(left)-1] != 1 && a-left[len(left)-1] != 2 {
left = append(left, a)
} else {
left = left[:len(left)-1]
}
}
if len(left) == 0 {
return true
} else {
return false
}
}
总结
- 解法1里面,我们使用的ascii码来判断,括号的顺序是否是对的。但是要注意的是,用ascii码来判断是有前提的, 就是题目里面说了字符串只会出现这6个字符,不会出现其他的字符。不然这样的判断是不对的。