20. Valid Parentheses [easy] (Python)
来源:互联网 发布:数控车床编程语言 编辑:程序博客网 时间:2024/06/05 07:45
题目链接
https://leetcode.com/problems/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(object): def isValid(self, s): """ :type s: str :rtype: bool """ pars = [None] parmap = {')': '(', '}': '{', ']': '['} for c in s: if c in parmap and parmap[c] == pars[len(pars)-1]: pars.pop() else: pars.append(c) return len(pars) == 1
思路二
实际上,通过观察可以发现:如果正要入栈的是右括号,而栈顶元素不是能与之消去的相应左括号,那么该输入字符串一定是无效的。于是,可以大的加快判断过程。
代码
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ pars = [None] parmap = {')': '(', '}': '{', ']': '['} for c in s: if c in parmap: if parmap[c] != pars.pop(): return False else: pars.append(c) return len(pars) == 1
说明
当然这里使用dict来存放括号的匹配关系不是必要的,直接通过字符之间ascii码的差值判断也是比较快的。
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51697963
- 20. Valid Parentheses [easy] (Python)
- 20. Valid Parentheses (Easy)
- 20.Valid Parentheses(Stack-Easy)
- Easy-题目47:20. Valid Parentheses
- Leetcode 20. Valid Parentheses (Easy) (cpp)
- 【leetcode】Valid Parentheses(easy)
- Valid Parentheses (EASY)
- [leetcode]20. Valid Parentheses ,有效的括号符串python实现【easy】
- [LeetCode] 020. Valid Parentheses (Easy) (C++/Java/Python)
- 20. Valid Parentheses Leetcode Python
- [leetcode:python]20.Valid Parentheses
- [Leetcode 20, Easy] Valid Parentheses
- 【Leetcode-Easy-20】 Valid Parentheses
- Leet Code OJ 20. Valid Parentheses [Difficulty: Easy]
- LeetCode-Easy部分中标签为String 20. Valid Parentheses
- Leet Code OJ 20. Valid Parentheses [Difficulty: Easy]
- 【leetcode】20. Valid Parentheses(Python & C++)
- Valid Parentheses python题解
- 云平台VPN功能对比
- Delphi代码标准文档
- Hadoop的Map侧join
- 导航栏特效(活动)
- jascript base64编解码,好东西
- 20. Valid Parentheses [easy] (Python)
- FreeMarker的认识及实例(一)
- 制作圆形头像
- mingw中安装 rtmpdump
- 安卓屏幕知识
- yii2框架-多语言版本切换(十三)
- TextView加文字阴影
- 并发和并行的区别
- 数学考试 1