1. 题目: 有效的括号
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
https://leetcode-cn.com/problems/valid-parentheses/
2. 方法1 暴力解法, 将所有配对括号替换为""
func isValid(s string) bool {
var length int
for length != len(s){
length = len(s)
s = strings.Replace(s, "{}","", -1)
s = strings.Replace(s, "()","", -1)
s = strings.Replace(s, "[]","", -1)
}
if len(s) > 0{
return false
}
return true
}
3. 方法2 Hash Table
将右括号作为hash key,遍历所有string
如果是左括号,入栈,如果遇到右括号,出栈,检查右括号对应的左括号是否匹配;
如果遍历过程中发现栈为空但是出现右括号,也是不匹配,例如"]"
func isValid(s string) bool {
hash := map[rune]rune{']': '[', '}': '{', ')': '('}
var stack []rune
for _, v := range s{
if _, ok := hash[v]; !ok{
stack = append(stack, v)
}else if len(stack) == 0 || hash[v] != stack[len(stack)-1]{
return false
}else{
stack = stack[:len(stack)-1]
}
}
if len(stack) != 0{
return false
}
return true
}