[Leetcode] 20. Valid Parentheses
2017-02-20 12:00
429 查看
Problem:
Given a string containing just the characters
The brackets must close in the correct order,
Idea:
Use the stack to solve this problem. For every incoming left mark, just push into the stack. Then, for every incoming right mark, just check the top item in the stack, if top item matches the incoming right mark, pop the top item, else return
Finally, after going throuth all items in string, just check if the stack is empty or not, if it is empty(means all pairs are matched and popped) then return
Solution:
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.
Idea:
Use the stack to solve this problem. For every incoming left mark, just push into the stack. Then, for every incoming right mark, just check the top item in the stack, if top item matches the incoming right mark, pop the top item, else return
False.
Finally, after going throuth all items in string, just check if the stack is empty or not, if it is empty(means all pairs are matched and popped) then return
True, else return
False.
Solution:
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ l = list() for item in s: if item == '(' or item == '{' or item == '[' : l.append(item) elif item == ')': if len(l) == 0: return False elif l[len(l)-1] == '(': l.pop() else: return False elif item == '}': if len(l) == 0: return False elif l[len(l)-1] == '{': l.pop() else: return False elif item == ']': if len(l) == 0: return False elif l[len(l)-1] == '[': l.pop() else: return False if len(l) == 0: return True else: return False
相关文章推荐
- 【LeetCode】20 Valid Parentheses (c++实现)
- LeetCode_Easy心得:20. Valid Parentheses(C语言)
- [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 OJ>Valid Parentheses【20】
- 20.[Leetcode]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
- LeetCode20——Valid Parentheses
- leetcode 20 Valid Parentheses