[勇者闯LeetCode] 20. Valid Parentheses
2017-03-10 23:47
351 查看
[勇者闯LeetCode] 20. Valid Parentheses
Description
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.
Information
Tags: Stack | StringDifficulty: Easy
Solution
用栈存储需要遇到的右括号。扫描字符串时遇到左括号则其对应的右括号入栈,遇到右括号则出栈并判断两个右括号是否相同,若不相同则返回false。扫描结束后,若栈内还有元素,则返回
false。
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ l = {"(": ")", "[": "]", "{": "}"} ans = [] for x in s: if x in l: ans.append(l[x]) elif (len(ans) == 0 or ans.pop() != x): return False return False if len(ans) > 0 else 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 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
- 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)
- Leetcode 20 Valid Parentheses stack的应用