给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
链接:https://leetcode-cn.com/problems/valid-parentheses
代码写的就是不优雅,比如头部处理这个地方。分成两类就行了嘛。太弱了
class Solution:
def isValid(self, s: str) -> bool:
ss = []
if len(s) == 0:
return True
for each in s:
if len(ss)>0:
a = ss[-1]
if (a,each) in [('(',')'),('[',']'),('{','}')]:
ss = ss[:-1]
elif each in [')',']','}']:
return False
else:
ss.append(each)
elif each in ['(','[','{']:
ss.append(each)
else:
return False
if len(ss)==0:
return True
else:
return False
class Solution(object):
def isValid(self, s):
stack = []
mapping = {")": "(", "}": "{", "]": "["}
for char in s:
if char in mapping:
top_element = stack.pop() if stack else '#'
if mapping[char] != top_element:
return False
else:
stack.append(char)
return not stack