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

leetcode20 Valid Parentheses 有效的括号

2017-10-13 16:00 501 查看
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
"""
if not s:
return False
symbol = ('(', ')', '{', '}', '[', ']')
s = list(s)
a = [val for val in s if val in symbol]
string = ''.join(a)
dict_a = ['()','[]','{}']
while len(string) > 0:
if '()' not in string and '[]' not in string and '{}' not in string:
return False
for i in dict_a:
string = string.replace(i,'')
return True

print Solution().isValid("([])")

思路:首先把字符串中多余字符全部去掉,只保留括号。随后不断替换(),[],{},当字符串长度不为0但却不包含()、[]、{}时,返回False,否则返回True。

优质解法:

def isValid(s):
stack = []
dict = {"]": "[", "}": "{", ")": "("}
for char in s:
if char in dict.values():
stack.append(char)
elif char in dict.keys():
if stack == [] or dict[char] != stack.pop():
return False
else:
return False
return stack == []

构建字典,利用栈的特性,如果一个字符等于字典的value,那么把它的另一部分存到栈里,并且下一次遇到的括号应该是就是它的另一部分,如果栈已经空了,还遇到括号的右边,或者遇到的括号不等于它的另一部分,返回false,如果最后这个栈还是空的,返回true。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python leetcode 算法