leetcode 20. Valid Parentheses
来源:互联网 发布:万花成女捏脸数据 编辑:程序博客网 时间:2024/05/22 08:19
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.
思路:创建一个栈来存放各种括号的左边部分,一个字典来存放每种括号配对。遍历整个字符串,每次先判断是否为左边部分:
(1)是,存入stack
(2)不是,判断是否stack为空,空的话就说明前面没有与这个右边部分匹配的,若不为空,还要判断是否与stack最后加入的字符配对
最后返回stack是否为空。
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] strdict = {"(": ")", "{": "}", "[": "]"} for char in s: if char in strdict: stack.append(char) else: if stack == [] or char != strdict[stack.pop()]: return False return stack == []
阅读全文
0 0
- 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] 20.Valid Parentheses
- [leetcode] 20. Valid Parentheses
- Leetcode 20. Valid Parentheses
- 20. Valid Parentheses LeetCode
- 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 20. Valid Parentheses
- leetcode-20. Valid Parentheses
- 第五周周总结
- JAVA【IO二】file类
- Building a HIPAA-Compliant Cybersecurity Program.pdf 免费下载
- Redis时延问题:高时延操作总结
- HTTP 和 Socket 的区别
- leetcode 20. Valid Parentheses
- Linux Centos6.5 安装Apache及优化
- POJ 1815 Friendship 最小割
- Android 借助 Python 实现自动打包上传 fir
- [坚毅:释放激情与坚持的力量].(美).安杰拉·达克沃思.扫描版.pdf 免费下载
- 多态与虚函数(虚表)
- Matlab中窗函数的简单使用
- 并查集(路径压缩)
- SpringMVC常用获取传递参数的方法