- class Solution:
- def isValid(self, s: str) -> bool:
- stack=[]
- for i in s:
- if i=='(':
- stack.append(')')
- elif i=='[':
- stack.append(']')
- elif i=='{':
- stack.append('}')
- elif not stack or stack[-1]!=i:
- return False
- else:
- stack.pop()
- return True if not stack else False
在匹配左括号的时候,右括号先入栈,就只需要比较当前元素和栈顶相不相等就可以了,比左括号先入栈代码实现要简单的多了!
法2:
- class Solution:
- def isValid(self, s: str) -> bool:
- dic={'(':')','[':']','{':'}'}
- stack=[]
- for i in s:
- if i in dic.keys():
- stack.append(dic[i])
- elif not stack or stack[-1]!=i:
- return False
- else:
- stack.pop()
- return not stack