leetcode20 Valid Parentheses 有效的括号
2017-10-13 16:00
501 查看
Given a string containing just the characters
determine if the input string is valid.
The brackets must close in the correct order,
all valid but
not.
给定字符串,包含(,),{,},[,],判断是不是有效的字符串。
括号必须以正确的顺序闭合,比如()、([])和()[]{}是有效的,但是(]和([)]是无效的。
解法:
思路:首先把字符串中多余字符全部去掉,只保留括号。随后不断替换(),[],{},当字符串长度不为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。
'(',
')',
'{',
'}',
'['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。
相关文章推荐
- LeetCode 20. Valid Parentheses--验证括号是否有效
- leetCode 20.Valid Parentheses (有效的括号) 解题思路和方法
- LeetCode 20 Valid Parentheses(有效的括号)
- LeetCode-20-Valid Parentheses(有效的括号)
- leetCode 20.Valid Parentheses (有效的括号) 解题思路和方法
- Leetcode刷题记——20. Valid Parentheses (有效的括号即括号匹配)
- LeetCode | 32. Longest Valid Parentheses——最长有效括号匹配长度
- [LeetCode]39. Longest Valid Parentheses最长有效括号对
- leetcode 32. Longest Valid Parentheses 最长有效括号长度
- leetcode Valid Parentheses 有效括号
- LeetCode Valid Parentheses 有效括号
- leetcode:Valid Parentheses(有效括号匹配)
- LeetCode 20. Valid Parentheses(括号校验)
- [LeetCode]35. Valid Parentheses有效括号
- LeetCode: Longest Valid Parentheses (求最长有效匹配括号子串的长度)
- 最长连续有效括号 Longest Valid Parentheses @LeetCode
- LeetCode( Valid Parentheses)有效的括号
- 【LeetCode刷题】有效的括号字符串Valid Parentheses(java)
- leetCode 32.Longest Valid Parentheses (有效的最大括号) 解题思路和方法
- LeetCode 20 Valid Parentheses(括号匹配)