【LEETCODE】20-Valid Parentheses
2015-12-14 16:40
393 查看
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.
思路:
遇到左括号,入栈
遇到了右括号,如果此时栈顶元素是相应的左括号,则True,其他情况为False
遇到一对后,弹出
[ ( ) ]
( ) [ ] { }
'(', ')',
'{', '}',
'[' and ']', determine if the input string is valid.
The brackets must close in the correct order,
"()" and "()[]{}" are all valid but
"(]" and "([)]" are not.
思路:
遇到左括号,入栈
遇到了右括号,如果此时栈顶元素是相应的左括号,则True,其他情况为False
遇到一对后,弹出
[ ( ) ]
( ) [ ] { }
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack=[] for i in range(len(s)): if s[i] == '(' or s[i] == '[' or s[i] == '{': stack.append(s[i]) if s[i] == ')': if stack == [] or stack.pop() != '(': return False if s[i] == ']': if stack == [] or stack.pop() != '[': return False if s[i] == '}': if stack == [] or stack.pop() != '{': return False if stack: return False else: return True
相关文章推荐
- (数据挖掘-入门-6)十折交叉验证和K近邻
- (数据挖掘-入门-5)基于内容的协同过滤与分类
- Android studio使用中遇到的坑——错误提示没有了(不出现了)
- 用border做纯CSS的三角形
- 归并排序
- git处理时的问题
- php数组函数-array_rand()
- 第十六周--验证算法(基数排序)
- OpenGL边用边学------2 经典照相机模型
- Oracle12c新特性之基本操作
- 运行时的“VFY: unable to resolve static field”错误
- 第7周项目4 队列数组
- autoencoder
- 窗口重叠,WS_CLIPCHILDREN和WS_CLIPSIBLINGS
- rpmbuild线上实战
- 第十六周项目(1):验证算法2——希尔排序
- 2743: [HEOI2012]采花
- Day1之OtherDemo
- (数据挖掘-入门-4)基于物品的协同过滤
- (数据挖掘-入门-3)基于用户的协同过滤之k近邻