Leetcode Day5 20. Valid Parentheses Python 栈的实现
来源:互联网 发布:淘宝拒签后怎么处理 编辑:程序博客网 时间:2024/05/16 08:26
今天leetcode遇到一道括号匹配的问题,首先想到用栈这种数据结构。
http://www.jianshu.com/p/1387fe93891c 查到这篇栈的实现,不错
进而想起前几天同学问我的list里的remove和pop有什么区别,今天查了一下这个答案不错
http://novell.me/master-diary/2014-06-05/difference-between-del-remove-and-pop-on.html
只是有一点需要更正,实践可知:在python3中,list.pop() == something 时并不会输出弹出的值
20. Valid Parentheses
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): if ("]" not in s and "}" not in s and ")" not in s): #防止类似"{(["这种只有左括号的输入 return False visualStack=[]#创建虚拟栈 for char in s: if char not in ["[","{","(","}",")","]" ]:#防止错误输入 return False if char in ["[" , "{" , "("]:#遇到左括号就入栈 visualStack.append(char) if len(visualStack)==0:#防止只有右括号的输入,比如")]}"就会在这里返回False return False else:#括号不匹配 if char == "}" and visualStack.pop()!="{": return False if char == ")" and visualStack.pop()!="(": return False if (char == "]") and visualStack.pop() != "[": return False return visualStack==[]#如果栈没弹空就代表左括号比右括号多sol=Solution()print ("result is",sol.isValid("([]"))
这个方法虽然笨但是我竟然写了好久T^T,跑了45ms
看到一个更简洁的做法:
class Solution: # @return a boolean def isValid(self, s): stack = [] dict = {"]":"[", "}":"{", ")":"("} for char in s: if char in dict.values(): stack.append(char) elif char in dict.keys(): if stack == [] or dict[char] != stack.pop(): return False else: return False return stack == []
阅读全文
0 0
- Leetcode Day5 20. Valid Parentheses Python 栈的实现
- 20. Valid Parentheses Leetcode Python
- [leetcode:python]20.Valid Parentheses
- Leetcode-Valid Parentheses-Python
- 【Leetcode】【python】Valid Parentheses
- [leetcode]20. Valid Parentheses ,有效的括号符串python实现【easy】
- [leetcode] 【栈】 20. Valid Parentheses
- 【Leetcode】20. Valid Parentheses【栈】
- 【leetcode】20. Valid Parentheses(Python & C++)
- LeetCode中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
- [leetcode] 20. Valid Parentheses
- OC一些不常用的函数
- 摘抄路遥《人生》
- 基于管道化和事件驱动模型的Web请求处理(二)
- codeforces 810 C
- 关于热更新动态加载替换application相关1
- Leetcode Day5 20. Valid Parentheses Python 栈的实现
- mac下Hadoop、HDFS、Spark环境的安装和搭建
- HDU 1536 S-Nim 博弈论-SG定理
- Jackson2库基础用法-Java json 序列化
- python使用模块chardet判断字符编码
- 进阶篇:3.10)铝型材(铝挤)件设计;
- 文本查询程序再探(C++primer5th)
- 热更新2
- Spring boot 打成jar包问题总结