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

LeetCode: 20. Valid Parentheses

2016-10-14 17:31 369 查看
题目:

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.

题意:

配对括号是否一致

题解:

class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
cur=[]
count=0
for i in range(len(s)):
if s[i] in [')', ']', '}'] and count==0:
return False
if s[i] in ['(', '[', '{']:
cur.append(s[i])
count=count+1
elif (count>0) and (s[i]==')' and cur[count-1]=='(') or (s[i]==']' and cur[count-1]=='[') or (s[i]=='}' and cur[count-1]=='{'):
del cur[count-1]
count=count-1
else:
return False
if count==0:
return True
else:
return False
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python leetcode