题目描述:

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

有效字符串需满足:

  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. 一些常用的mysql语句实例-以后照写2

    specification: 规范, 规格, 产品规范, 产品规格, 技术规范, 产品说明书. 如: create_specification, 等等 创建数据库时, 显式地指明, 字符集: crea ...

  2. JavaI/O(输入/输出)

    File类 通过File类可以在程序中操作文件和目录,File能新建.删除.重命名文件和目录,但是不能访问文件内容本身. 理解I/O流 流(stream)是从起源(source)到接收(sink)的有 ...

  3. iframe初始化属性

    <iframe id="user" src="xxx.html" frameborder="0" width="" ...

  4. BZOJ 4399 魔法少女LJJ(线段树合并)

    题意 https://www.lydsy.com/JudgeOnline/problem.php?id=4399 思路 码农题,需要一定代码功底.方法很暴力,先将权值离散,表示在线段树里储存的位置,每 ...

  5. MongoDB集群配置笔记一

    MongoDB 的部署方案有单机部署.复本集(主备)部署.分片部署.复本集与分片混合部署.混合的部署方式如图: 分片集群的构造 (1)mongos :数据路由,和客户端打交道的模块.mongos本身没 ...

  6. Writing device drivers in Linux: A brief tutorial

    “Do you pine for the nice days of Minix-1.1, when men were men and wrote their own device drivers?”  ...

  7. java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]

    本文为博主原创,未经允许不得转载: 被坑了好长时间的bug,差点就要重新配置环境,重新下载,重新开始的境遇.在此记录一下: 首先展示一下报错的异常: -Apr- ::] org.apache.cata ...

  8. 解决Linux服务器磁盘空间不足的问题

    在linux服务器执行程序时报错: awk: write failure (No space left on device)awk: close failed on file /dev/stdout ...

  9. 【NOI 2009】诗人小G

    Problem Description 小 \(G\) 是一个出色的诗人,经常作诗自娱自乐.但是,他一直被一件事情所困扰,那就是诗的排版问题. 一首诗包含了若干个句子,对于一些连续的短句,可以将它们用 ...

  10. HTTPS 如何保证数据传输的安全性

    为什么需要 HTTPS? 我们知道 HTTP 是一个纯文本传输协议,对传输过程中的数据包不进行加密,是明文传输,那这样的话对于介于在发送端和接收端之间的任何 一个节点都能知道传输的内容,这些节点可能是 ...