题目
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
1、左括号必须用相同类型的右括号闭合。
2、左括号必须以正确的顺序闭合。
Python实现
class Solution:
def isValid(self, s: str) -> bool:
q = []
d = {')':'(','}':'{',']':'['}
for i in s:
if len(q)>=1:
if d.get(i,None)==q[-1]:
q.pop(-1)
continue
q.append(i)
return not q
Golang实现
func isValid(s string) bool {
n := len(s)
d:= map[byte]byte{
')': '(',
']': '[',
'}': '{'}
q := []byte{}
for i:= 0 ;i<n;i++{
if len(q)>=1{
if d[byte(s[i])]==q[len(q)-1]{
q = q[:len(q)-1]
continue
}
}
q = append(q,byte(s[i]))
}
return len(q)==0
}