leetcode20 Valid Parentheses 有效的括号
来源:互联网 发布:区域设置软件中文版 编辑:程序博客网 时间:2024/05/20 01:34
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 Trueprint 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。
阅读全文
0 0
- leetcode20 Valid Parentheses 有效的括号
- Valid Parentheses 有效括号
- Longest Valid Parentheses 最长的有效括号
- 【LeetCode】- Valid Parentheses(有效的括号)
- LeetCode-20-Valid Parentheses(有效的括号)
- Valid Parentheses有效的括号序列
- leetcode Valid Parentheses 有效括号
- LeetCode20——Valid Parentheses(括号匹配问题,使用栈的知识)
- LeetCode20 Valid Parentheses的java 题解
- LeetCode20: Valid Parentheses
- [LeetCode20]Valid Parentheses
- leetcode20-Valid Parentheses
- LeetCode20:Valid Parentheses
- LeetCode20:Valid Parentheses
- leetcode20. Valid Parentheses
- LeetCode20 Valid Parentheses
- LeetCode20. Valid Parentheses
- Leetcode20: Valid Parentheses
- 4. 控制、监视、测量范围
- LeetCode-Remove K Digits
- 干了这杯Java之ArrayList存储一个有序元素合集
- IndentationError:expected an indented block错误解决
- H5 搭建控制台错误
- leetcode20 Valid Parentheses 有效的括号
- Mysql数据库表结构优化
- 巧解HorizontalListView需求,支持多选。
- 在一个字符串中个找到只出现一次的第一个字符
- 数据集合的重用
- 前端_全选、反选、批量删除、表格
- 阿里云vps上mysql挂掉的解决办法
- Shell更改一般文件或目录权限的脚本
- QTableWidget常用技巧