您的位置:首页 > 编程语言 > Python开发

20. Valid Parentheses leetcode Python 2016 new Season

2016-01-07 10:41 741 查看
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.

Show Company Tags

Show Tags

Show Similar Problems

Have you met this question in a real interview? 
Yes
 
No

Discuss

need O(n) time to go through the whole array and worst case O(n) space to store the array.

class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for index in range(len(s)):
current_string = s[index]
if current_string == '(' or current_string == '[' or current_string == '{':
stack.append(current_string)
if current_string == ')':
if not stack or stack.pop() != '(':
return False
if current_string == ']':
if not stack or stack.pop() != '[':
return False
if current_string == '}':
if not stack or stack.pop() != '{':
return False
if stack:
return False
return True
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: