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 描述 在某 ...
随机推荐
- img的基线对齐问题
http://blog.csdn.net/u011997156/article/details/44806523
- 如何在gvim中安装autoproto自动显示函数原型
cankao: http://www.vim.org/scripts/script.php?script_id=1553 注意, 在gvim中执行的命令, :foo和:!foo 的区别, 跟vim一样 ...
- SPOJ 687 REPEATS - Repeats
题意 给定字符串,求重复次数最多的连续重复子串 思路 后缀数组的神题 让我对着题解想了快1天 首先考虑一个暴力,枚举循环串的长度l,然后再枚举每个点i,用i和i+l匹配,如果匹配长度是L,这个循环串就 ...
- [jsp] - jsp引入c标签出错
jsp引入c标签出错, 因为之前使用thymeleaf,将jsp的依赖删除了.(这里应该采用注释而非删除,但以为项目就一直用thymeleaf了) <%@ taglib uri="ht ...
- 【matlab】笔记_1
基本操作 ans 最近计算的答案 clc 清除命令行窗口 diary 将命令行窗口文本保存到文件中 矩阵 用逗号 (,) 或空格分隔各行元素. 用分号(;)分隔各列元素. a':装置矩阵. 要执行元素 ...
- JQuery---高级类选择器
1.ContentFilters 1.1 语法:$('div:contains(edu)').css('backgroundColor','yellow'); 只看div 本身是否包含内容 1.2 语 ...
- MongoDB集群配置笔记二(实战)
单台mongodb配置文件: dbpath=/opt/mongodb/data logpath=/opt/mongodb/logs/mongodb.log logappend=true fork=tr ...
- PTA 7-2 列车调度(25 分)
7-2 列车调度(25 分) 火车站的列车调度铁轨的结构如下图所示. 两端分别是一条入口(Entrance)轨道和一条出口(Exit)轨道,它们之间有N条平行的轨道.每趟列车从入口可以选择任意一条轨道 ...
- 数据结构和算法with Python
http://www.math.pku.edu.cn/teachers/qiuzy/ds_python/courseware/index.htm
- 7、nginx的upstream及fastcgi模块应用
ngx_http_proxy_module, ngx_http_upstream_module ngx_http_proxy_module:实现反向代理及缓存功能 proxy_pass http: ...