设为首页 加入收藏

TOP

[leetcode] Valid Parentheses @Python
2015-07-20 17:35:15 来源: 作者: 【 】 浏览:2
Tags:leetcode Valid Parentheses @Python
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
?
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
?
Trick:?
?
Data structure: stack. LIFO (Last in first out)
?
复制代码
class Solution:
? ? # @return a boolean
? ? def isValid(self, s):
? ? ? ? stack = []
? ? ? ? left, right = '([{', ')]}'
? ? ? ? for i in s:
? ? ? ? ? ? if i in left:
? ? ? ? ? ? ? ? stack.append(i); continue
? ? ? ? ? ? for j in range(3):
? ? ? ? ? ? ? ? if right[j] == i:
? ? ? ? ? ? ? ? ? ? if not stack or stack[-1] != left[j]:
? ? ? ? ? ? ? ? ? ? ? ? return False
? ? ? ? ? ? ? ? ? ? else:
? ? ? ? ? ? ? ? ? ? ? ? stack.pop()
? ? ? ? ? ? ? ? ? ? ? ? continue
? ? ? ? return not stack
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇[leetcode] Longest Valid Parent.. 下一篇hdu 1069 Monkey and Banana (dp)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·有没有适合新手练习 (2025-12-26 01:48:47)
·用清华镜像网怎么下 (2025-12-26 01:48:44)
·请比较Python和R语言 (2025-12-26 01:48:42)
·JAVA现在的就业环境 (2025-12-26 01:19:24)
·最好的java反编译工 (2025-12-26 01:19:21)