您的位置:首页 > 其它

【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
遇到一对后,弹出
[ ( ) ]
( ) [ ] { }

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: