leetcode Valid Parentheses python

# 解题思路: 
# 创建一个字典映射关系 dicts
# 使用一个栈stk 遍历字符串s 得到一个新的字符串curItem 如果lastItem在dicts中的value和它相等 不做任何操作
# 如果不等 入栈 有lastItem的 先append lastItem 然后是curItem
#
# 最后判断如果stk为空说明所给字符串匹配 return true class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
strLen = len(s)
if strLen <= 1:
return False dicts={"(":")","{":"}","[":"]"}
stk=list()
for i in xrange(strLen):
lastItem=None
if len(stk) > 0:
lastItem = stk.pop()
curItem = s[i]
if len(stk) == 0 and lastItem == None:
stk.append(curItem)
elif dicts.has_key(lastItem) and curItem == dicts[lastItem]:
pass
else:
if lastItem:
stk.append(lastItem)
stk.append(curItem)
if len(stk) == 0:
return True
else:
return False
上一篇:通配符的匹配很全面, 但无法找到元素 'tx:annotation-driven' 的声明


下一篇:02、Unicode 汉字转码小工具