LeetCode-20 valid parenthesis
2018-03-21 11:48
405 查看
题目:括号匹配问题
Given a string containing just the characters
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
"""
根据tag给的提示,应该是用到了stack的思想
构建一个字典,将右括号放在keys,左括号放在values
如果s中的元素在values中,压栈append
如果在keys中:栈为空或没有匹配的左括号,false
其他情况false
最终栈应该是空的,都对应的pop掉了
"""
dict = {'}':'{',']':'[',')':'('}
stack = []
for ch in s:
if ch in dict.values():
stack.append(ch)
elif ch in dict.keys():
if stack == [] or dict[ch] != stack.pop():
return False
else:
return False
return stack == []
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.解题: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:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
"""
根据tag给的提示,应该是用到了stack的思想
构建一个字典,将右括号放在keys,左括号放在values
如果s中的元素在values中,压栈append
如果在keys中:栈为空或没有匹配的左括号,false
其他情况false
最终栈应该是空的,都对应的pop掉了
"""
dict = {'}':'{',']':'[',')':'('}
stack = []
for ch in s:
if ch in dict.values():
stack.append(ch)
elif ch in dict.keys():
if stack == [] or dict[ch] != stack.pop():
return False
else:
return False
return stack == []
相关文章推荐
- Leetcode 20 Valid Parenthesis
- LeetCode - Valid Parenthesis
- leetcode20 Valid Parentheses 有效的括号
- leetcode 20 Valid Parentheses
- leetcode(9).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(C++ Java Python)
- 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(有效的括号)
- [leetcode Q20] Valid Parentheses