题目描述:

给定一个只包括 '('')''{''}''['']' 的字符串,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

方法1:

  遇到左括号压入list中,遇到右括号时先判断list是否为空,是则返回false,否则弹出一个字符与其进行比较,匹配则continue 否则返回false   (32ms)

 class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
lists = []
i = 0
if len(s) == 1:
return False
elif len(s) == 0:
return True
while i < len(s):
c = s[i]
if c =='(' or c == '[' or c == '{':
# if i + 1 != len(s):
# if s[i+1] != ')' and s[i+1] != ']' and s[i+1] != '}':
# if c < s[i+1]:
# return False
#([])这种竟然算对,好吧
lists.append(c) elif c == ')': if len(lists) != 0:
t = lists.pop()
if t == '(':
i+=1
continue
else:
return False
else:
return False
elif c == ']': if len(lists) != 0:
t = lists.pop()
if t == '[':
i+=1
continue
else:
return False
else:
return False
elif c == '}': if len(lists) != 0:
t = lists.pop()
if t == '{':
i+=1
continue
else:
return False
else:
return False
i += 1 if len(lists) != 0:
return False
else:
return True

简洁版:(28ms)

 class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for c in s:
if c == '(' or c == '{' or c == '[':
stack.append(c)
elif not stack:
return False
elif c == ')' and stack.pop() != '(':
return False
elif c == '}' and stack.pop() != '{':
return False
elif c == ']' and stack.pop() != '[':
return False
return not stack

利用字典:(24ms)

 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

时间最短:(20ms)

  用抛出异常的方式把类似)()剔除

 class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
try:
stack = []
for key in s :
if(key == '(' or key == '[' or key == '{'):
stack.append(key)
else:
if((key == ')' and stack.pop() == '(') or
(key == ']' and stack.pop() == '[') or
(key == '}' and stack.pop() == '{')):
pass
else:
return False
if(len(stack) == 0):
return True
except IndexError:
return False
return False

2018-07-22 18:48:45

LeetCode--020--括号匹配的更多相关文章

  1. leetcode 栈 括号匹配

    https://oj.leetcode.com/problems/valid-parentheses/ 遇到左括号入栈,遇到右括号出栈找匹配,为空或不匹配为空, public class Soluti ...

  2. leetcode 20 括号匹配

    class Solution { public: bool isValid(string s) { stack<char> result; for(char c:s){ if(c == ' ...

  3. LeetCode 20 Valid Parentheses (括号匹配问题)

    题目链接 https://leetcode.com/problems/valid-parentheses/?tab=Description   Problem: 括号匹配问题. 使用栈,先进后出!   ...

  4. 《LeetBook》leetcode题解(20):Valid Parentheses[E]——栈解决括号匹配问题

    我现在在做一个叫<leetbook>的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,需要的同学可以去看看 书的地址:https://hk029.g ...

  5. LeetCode 第20题--括号匹配

    1. 题目 2.题目分析与思路 3.代码 1. 题目 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效. 有效字符串需满足: 左括号必须用相同类型的右括号闭 ...

  6. [Leetcode][020] Valid Parentheses (Java)

    题目在这里: https://leetcode.com/problems/valid-parentheses/ [标签]Stack; String [个人分析]这个题应该算是Stack的经典应用.先进 ...

  7. 括号匹配 区间DP (经典)

    描述给你一个字符串,里面只包含"(",")","[","]"四种符号,请问你需要至少添加多少个括号才能使这些括号匹配起来 ...

  8. YTU 3003: 括号匹配(栈和队列)

    3003: 括号匹配(栈和队列) 时间限制: 1 Sec  内存限制: 128 MB 提交: 2  解决: 2 [提交][状态][讨论版] 题目描述 假设一个表达式中只允许包含三种括号:圆括号&quo ...

  9. [原]NYOJ 括号匹配系列2,5

    本文出自:http://blog.csdn.net/svitter 括号匹配一:http://acm.nyist.net/JudgeOnline/problem.php?pid=2 括号匹配二:htt ...

  10. POJ C程序设计进阶 编程题#4:括号匹配问题

    编程题#4:扩号匹配问题 来源: POJ(Coursera声明:在POJ上完成的习题将不会计入Coursera的最后成绩.) 注意: 总时间限制: 1000ms 内存限制: 65536kB 描述 在某 ...

随机推荐

  1. Item的anchors属性

    1.anchors group: anchors.top : AnchorLine anchors.bottom : AnchorLine anchors.left : AnchorLine anch ...

  2. How to install Maven on Windows

    To install Apache Maven on Windows, you just need to download the Maven’s zip file, and Unzip it to ...

  3. 三元运算符代替if-else

    main(List<String> args) { int age = 60; String status = age < 50 ? "Still young" ...

  4. 如何合并ts文件?

    答: 使用ffmpeg工具,使用方法如下: ffmpeg -i <m3u8 file name> <output file name> 注意:要先将m3u8文件中描述的ts文件 ...

  5. 论文笔记:Learning Dynamic Memory Networks for Object Tracking

    Learning Dynamic Memory Networks for Object Tracking  ECCV 2018Updated on 2018-08-05 16:36:30 Paper: ...

  6. 深度学习课程笔记(三)Backpropagation 反向传播算法

    深度学习课程笔记(三)Backpropagation 反向传播算法 2017.10.06  材料来自:http://speech.ee.ntu.edu.tw/~tlkagk/courses_MLDS1 ...

  7. Unity3D学习笔记(三十八):VR开发

    设备安装:HTC View   驱动安装:Steam - SteamVR 设备激活 Unity开发 下载安装开发包 Asset Store - SteamVR Plugin SteamVRDemo1- ...

  8. 洛谷P1803 凌乱的yyy dp

    我要日更嘤嘤嘤>_< 原题戳>>https://www.luogu.org/problem/show?pid=1803<<(其实是戳不动的,复制粘贴吧) 题目背景 ...

  9. Latex: 使 tabular 居中

    参考: How to center the table in Latex Latex: 使 tabular 居中 解决方法1: { \centering \begin{tabular} ... \en ...

  10. 移动端开发:使用jQuery Mobile还是Zepto

    原:http://blog.csdn.net/liubinwyzbt/article/details/51446771 jQuery Mobile和Zepto是移动端的js库.jQuery Mobil ...