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
原文地址:https://www.cnblogs.com/allenhaozi/p/4985114.html