设为首页 加入收藏

TOP

[leetcode] Valid Parentheses @Python
2015-07-20 17:35:15 来源: 作者: 【 】 浏览:1
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)

评论

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

·Java 并发工具类:提 (2025-12-25 20:25:44)
·Java面试技巧:如何 (2025-12-25 20:25:41)
·Java并发编程中的线 (2025-12-25 20:25:38)
·C 语言 - cppreferen (2025-12-25 19:50:27)
·《C 语言入门教程》 (2025-12-25 19:50:23)