原题链接:https://leetcode.com/problems/valid-parentheses/
解题思路:首先建立一个字典,keys为左括号,values为右括号。采用栈的思想。
1、当栈为空时,如果出现的下一个元素为右括号,直接return false
2、当栈的最后一个符号对应的value为当前的item时(如stack[-1]=’(’,当前item为’)")则pop stack,否则使item入栈
3、当遍历完所有item时,stack为空,则return true,否则return false
代码:
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
dictionary = {
'(': ')',
'[': ']',
'{': '}'
}
stack = []
if len(s) == 0:
return True
for item in s:
if item in dictionary.values():
if stack == []:
return False
elif item == dictionary[stack[-1]]:
stack.pop()
else:
return False
else:
stack.append(item)
if stack == []:
return True
else:
return False