博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
20. Valid Parentheses
阅读量:4598 次
发布时间:2019-06-09

本文共 1666 字,大约阅读时间需要 5 分钟。

1.题目:

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.

这个题目不难理解,就是我们平时写程序时候,小括号,中括号,大括号都要对应的包起来,否则就有问题。

现在给定一个字符串,需要你来判断一下这个字符串是否满足该要求!

2.代码:

该问题,用栈的后进先出结构就很容易解决了。分三种情况,1. 下一个元素是左边的,直接入栈;2.下一个元素是右边的,要看能否和栈顶元素匹配,不匹配当然有问题了;3.匹配的话,刚好抵消掉栈顶元素,栈顶元素出栈;最后,判断下栈有没有完全抵消即可。

# -*-coding:utf-8-*-class Solution(object):    def isValid(self, s):        """        :type s: str        :rtype: bool        """        left = ['(','[','{
'] right = [')',']','}'] l = list(s) stack = [] left_count,right_count = 0,0 #从左到右遍历字符串 while len(l)>0: #如果这个字符是在left中,就写进stack if l[0] in left: stack.append(l[0]) #如果这个字符在right中,先判断stack,如果stack为空,直接返回False,如果stack的最后一位和该字符不匹配(否则会出现交叉情况,例如([)]),也直接返回False #如果stack的最后一位和该字符刚好匹配,则从stack中弹出匹配到的字符 elif l[0] in right: if len(stack)==0:return False #print (l[0],' ',stack[-1]) #print (right.index(')')) if right.index(l[0])==left.index(stack[-1]): stack.pop() else: return False #如果输入不是这些,也返回False,题目中说了 just the characters,只有这六个字符 else: return False l.remove(l[0]) #最后判断stack是否刚好抵消 return len(stack)==0 if __name__=='__main__': s = '((' a = Solution() print (a.isValid(s))

 

转载于:https://www.cnblogs.com/yuanzhaoyi/p/6098248.html

你可能感兴趣的文章
Saltstack_使用指南18_API
查看>>
javascript 之 浏览器宽度、高度总结
查看>>
python实例31[列出目录下所有的文件到txt]
查看>>
修复iPhone上submit按钮bug
查看>>
backbone collection add 事件回调参数
查看>>
转载:XGBOOST算法梳理
查看>>
EM算法
查看>>
istringstream。PKU2493 Rdeaalbe。
查看>>
linux监控系统的状态
查看>>
编码风格
查看>>
Linux的ls命令在Windows中的应用
查看>>
4.Spring注解+SpringMVC注解+MyBatis注解(动态sql)
查看>>
算法导论 CLRS 24.1-5 解答
查看>>
接了个私单,结果对方有部分尾款迟迟不付,还好有留了个后门
查看>>
keep the bar green to keep the code clean——Junit详解(二)
查看>>
system表空间空间解决(ORA-00604 ORA-01653 ORA-02002)
查看>>
【原创】敏捷软件产品/项目开发管理流程(一)
查看>>
Node.js中的express框架,修改内容后自动更新(免重启),express热更新
查看>>
团队每日冲刺04
查看>>
oracle中的decode的使用
查看>>