【LeetCode 20】Valid Parentheses(Python)
2017-11-09 22:55
417 查看
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.
题目分析:给定一个字符串包含的字符只能在这些中’(‘, ‘)’, ‘{‘, ‘}’, ‘[’ , ‘]’选择。判断输入的括号是否匹配。例如:[()] ->合法 [(}] ->不合法 ()) ->不合法
方法一:
思路:用数据结构里面的栈去做,最简单,也好懂。
在这里简单介绍一下栈,就是一个空的表,当要往表里添加元素的时候,只能在表的一段进行插入删除(就像一个水杯,只有一个开口,不管你想倒入水还是倒出水,都只能对那一个口操作)
栈的操作主要就是pop() 弹出最后输入的那个元素,append()添加一个元素进栈。栈内是有序排列的(按你插入元素的先后顺序,最先插入的元素就在杯子底,最后插入的元素当然也就摞到了杯子最上边)
代码:(可以成功提交)
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
题目分析:给定一个字符串包含的字符只能在这些中’(‘, ‘)’, ‘{‘, ‘}’, ‘[’ , ‘]’选择。判断输入的括号是否匹配。例如:[()] ->合法 [(}] ->不合法 ()) ->不合法
方法一:
思路:用数据结构里面的栈去做,最简单,也好懂。
在这里简单介绍一下栈,就是一个空的表,当要往表里添加元素的时候,只能在表的一段进行插入删除(就像一个水杯,只有一个开口,不管你想倒入水还是倒出水,都只能对那一个口操作)
栈的操作主要就是pop() 弹出最后输入的那个元素,append()添加一个元素进栈。栈内是有序排列的(按你插入元素的先后顺序,最先插入的元素就在杯子底,最后插入的元素当然也就摞到了杯子最上边)
代码:(可以成功提交)
class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ sa=[None] a={'}':'{',']':'[',')':'('} for i in s: if i in a and a[i]==sa[len(sa)-1]: sa.pop() else: sa.append(i) return if len(sa)==1 ''' 这下面的内容是为了将最后测验结果可视化,提交的时候可以不写 if len(sa)==1: print("false") else:print("true") ''' d=Solution() #最后这三行是便于自己在编译器里运行进行检查,提交的时候写不写都行 c=d.isValid(['[{}]']) print(c)
相关文章推荐
- 20. Valid Parentheses Leetcode Python
- 20. Valid Parentheses leetcode Python 2016 new Season
- [leetcode:python]20.Valid Parentheses
- LeetCode 20 Valid Parentheses (C,C++,Java,Python)
- python写算法题:leetcode: 20. Valid Parentheses
- leetcode 20. Valid Parentheses——python(easy)——使用了堆栈
- 【leetcode】20. Valid Parentheses(Python & C++)
- LeetCode 20 — Valid Parentheses(C++ Java Python)
- LeetCode *** 20. Valid Parentheses
- leetcode 20. Valid Parentheses ---java
- leetcode:20 Valid Parentheses-每日编程第三十七题
- [leetcode]Longest Valid Parentheses @ Python
- 【Leetcode】【python】Valid Parentheses
- LeetCode - 20. Valid Parentheses
- leetcode(20. Valid Parentheses)
- [leetcode-20]Valid Parentheses(java)
- leetcode 20. Valid Parentheses
- 【leetcode】20. Valid Parentheses
- [LeetCode]题解(python):020-Valid Parentheses
- leetcode20:Valid Parentheses