leetcode 20. Valid Parentheses
2017-11-18 10:49
471 查看
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是否为空。
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 == []
相关文章推荐
- Leetcode 20 Valid Parentheses stack的应用
- LeetCode---(20)Valid Parentheses
- Java [leetcode 20]Valid Parentheses
- [Leetcode] 20. Valid Parentheses(Stack)
- leetcode 20. Valid Parentheses
- 20. Valid Parentheses-leetcode-java
- leetcode 20 Valid Parentheses 括号匹配
- Leetcode刷题记——20. Valid Parentheses (有效的括号即括号匹配)
- leetcode-20 Valid Parentheses
- [leetcode]20. Valid Parentheses(Java)
- 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-每日编程第三十七题
- [LeetCode20]Valid Parentheses
- LeetCode20: Valid Parentheses
- [C++]LeetCode 20: Valid Parentheses(判断运算符有效性)