LeetCode--020--括号匹配
题目描述:
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
方法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--括号匹配的更多相关文章
- leetcode 栈 括号匹配
https://oj.leetcode.com/problems/valid-parentheses/ 遇到左括号入栈,遇到右括号出栈找匹配,为空或不匹配为空, public class Soluti ...
- leetcode 20 括号匹配
class Solution { public: bool isValid(string s) { stack<char> result; for(char c:s){ if(c == ' ...
- LeetCode 20 Valid Parentheses (括号匹配问题)
题目链接 https://leetcode.com/problems/valid-parentheses/?tab=Description Problem: 括号匹配问题. 使用栈,先进后出! ...
- 《LeetBook》leetcode题解(20):Valid Parentheses[E]——栈解决括号匹配问题
我现在在做一个叫<leetbook>的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,需要的同学可以去看看 书的地址:https://hk029.g ...
- LeetCode 第20题--括号匹配
1. 题目 2.题目分析与思路 3.代码 1. 题目 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效. 有效字符串需满足: 左括号必须用相同类型的右括号闭 ...
- [Leetcode][020] Valid Parentheses (Java)
题目在这里: https://leetcode.com/problems/valid-parentheses/ [标签]Stack; String [个人分析]这个题应该算是Stack的经典应用.先进 ...
- 括号匹配 区间DP (经典)
描述给你一个字符串,里面只包含"(",")","[","]"四种符号,请问你需要至少添加多少个括号才能使这些括号匹配起来 ...
- YTU 3003: 括号匹配(栈和队列)
3003: 括号匹配(栈和队列) 时间限制: 1 Sec 内存限制: 128 MB 提交: 2 解决: 2 [提交][状态][讨论版] 题目描述 假设一个表达式中只允许包含三种括号:圆括号&quo ...
- [原]NYOJ 括号匹配系列2,5
本文出自:http://blog.csdn.net/svitter 括号匹配一:http://acm.nyist.net/JudgeOnline/problem.php?pid=2 括号匹配二:htt ...
- POJ C程序设计进阶 编程题#4:括号匹配问题
编程题#4:扩号匹配问题 来源: POJ(Coursera声明:在POJ上完成的习题将不会计入Coursera的最后成绩.) 注意: 总时间限制: 1000ms 内存限制: 65536kB 描述 在某 ...
随机推荐
- default activity not found的问题
莫名其妙的同一个project下的所有modlue全都出现了这个问题,在网上查了一些解决方法,总结一下就是在运行时把default activity改成nothing,这个把活动都搞没了肯定不行.还有 ...
- 关于二进制——lowbit运算
lowbit(n)意思即为找出n在二进制表示下最后一位1即其后面的0所组成的数值,别的东西算法书上有,这里提出一个重要的公式 lowbit(n)=n&(~n+1)=n&(-n),这个有 ...
- ODAC(V9.5.15) 学习笔记(三)TOraSession(2)
2. 事务相关 名称 类型 说明 AutoCommit Boolean 是否自动提交事务 注意:只有当TOraSession和TOraQuery的AutoCommit都为True时才对每个数据库操作自 ...
- 搭建git 服务器
Gogs 什么是 Gogs? Gogs 是一款极易搭建的自助 Git 服务. https://gogs.io/docs
- 论文笔记:Variational Capsules for Image Analysis and Synthesis
Variational Capsules for Image Analysis and Synthesis 2018-07-16 16:54:36 Paper: https://arxiv.org/ ...
- ES6模块化操作
在ES5中我们要进行模块化操作需要引入第三方类库,随着前后端分离,前端的业务日渐复杂,ES6为我们增加了模块化操作.模块化操作主要包括两个方面. export :负责进行模块化,也是模块的输出. im ...
- python实现八皇后问题
import random def judge(state, nextX): #判断是否和之前的皇后状态有冲突 nextY = len(state) for i in range(nextY): if ...
- HashMap分析
原文链接:http://www.cnblogs.com/chengxiao/p/6059914.html 一.什么是哈希表 在讨论哈希表之前,我们先大概了解下其他数据结构在新增,查找等基础操作执行性能 ...
- js实现网站首页分享滑块
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8&quo ...
- 添加删除tag
为某个分支打tag git tag -a v1. 9fceb02 删除tag git tag -d test_tag git push origin --delete tag test_tag 推送: ...