有效的括号
valid parentheses
题目:
Given a string s 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. (正确的顺序)
这道题:堆栈的思维
先进后出,要配成对
误区:1) 最开始我没有看懂题,认为 ([)也是对的,但是不是的,是需要配好对。应该用堆栈。
2) 括号只有这三种,“(”," [", " {", 所以这三个肯定是要遍历的。
把括号一切左边的部分都压入到堆栈中,用右边的来匹配。
class Solution:
def isValid(self, s: str) -> bool:
if len(s)==0:
return True
stack=[]
for c in s:
if c=='(' or c=='[' or c=='{':
stack.append(c)
else:
if len(stack)==0:
return False
else:
d=stack.pop()
if c == ')' and d!='(':
return False
elif c ==']' and d!='[':
return False
elif c =='}' and d!='{':
return False
if len(stack)!=0:
return False
else:
return True
这是一个easy的题,但是我遇到了很多问题。
(1)len(s)=0 是true的,但是我没有考虑到
(2)若list是空,pop()会出错。
(3) if c == ‘)’ and d!=’(’, 则return False。但是最开始我写的是:
if c == ‘)’ and d==’(’, 写的很不顺利。
(4)忘记了len(stack) 不为空的情况。