题目描述
*给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*
我的解答
class Solution:
def isValid(self, s: str) -> bool:
stack = [s[0]]
dict = {
'(': ')',
'[': ']',
'{': '}'
}
length = len(s)
i = 1
while (i < length):
if stack and stack[-1] in dict and dict[stack[-1]] == s[i] :
stack.pop()
else:
stack.append(s[i])
i += 1
if not stack:
return True
else:
return False
我的收获
1、取栈顶元素:stack[-1]
2、字典取值用中括号,而不是用圆括号,卡这卡半天:dict[stack[-1]]
执行了五次才通过!!!
主要是一直卡在if判断这里:if stack and stack[-1] in dict and dict[stack[-1]] == s[i] and stack[-1] in dict:
- 一开始我只写了if dict[stack[-1]] == s[i] :,但是它在栈为空的时候就会报错,以内此时stack[-1]不存在
- 然后就变成if stack and dict[stack[-1]] == s[i] :解决了上面报错,又有了新问题,当输入键值不在dict中时,就会报错,如栈顶元素为’)'
- 最后判断语句变成了ifstack[-1] in dict and stack and dict[stack[-1]] == s[i] :,与最终判断语句只是变了个位置,还是报错!!!
- 最后换了位置就成功了,说明and执行顺序是从左向右的。
- **最后的最后,如果在判断语句中同时存在or,and,not,先计算not,然后and,最后or。**当然有括号就先上括号