【LeetCode】20. Valid Parentheses
来源:互联网 发布:windows 10 iot 编辑:程序博客网 时间:2024/06/15 22:24
原题连接: https://leetcode.com/problems/valid-parentheses/
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.
这道题当初废了我不少时间,竟然只是个easy的题目。哈哈,一开始想歪了就没有想到用Stack。也不知道为什么别人的解法都能想到用Stack。
首先题目要求”()[]{}”类似这样出现,隐含条件是“([{()}])”这样的嵌套也是可以的。
方法很多很灵活,但基本都是利用Stack先进先出可以处理对称问题的特性。
public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); for(char c:s.toCharArray()){ if(c=='('){ stack.push(')'); }else if(c=='['){ stack.push(']'); }else if(c=='{'){ stack.push('}'); }else if(stack.isEmpty()||stack.pop()!=c){ return false; } } return stack.isEmpty(); }
public boolean isValid(String s){ int length = 0; do{ length=s.length(); s=s.replace("()", "").replace("[]", "").replace("{}", ""); //记得将s赋值 }while(length!=s.length()); return s.length()==0; }
这个方法的思路非常简单暴力,有点神似俄罗斯方块的逻辑。
不停循环替换,然后比较长度。长度相同的情况下(替换完毕)停止替换。 —这是个常见思路。
s.replace("a",""); //并不会对s造成改变,生成的是一个新的字符串
0 0
- LeetCode 20. Valid Parentheses
- [LeetCode] 20.Valid Parentheses
- LeetCode --- 20. Valid Parentheses
- LeetCode 20.Valid Parentheses
- [Leetcode] 20. Valid Parentheses
- 【leetcode】20. Valid Parentheses
- [leetcode] 20.Valid Parentheses
- [leetcode] 20. Valid Parentheses
- Leetcode 20. Valid Parentheses
- 20. Valid Parentheses LeetCode
- leetcode 20. Valid Parentheses
- 【LeetCode】20. Valid Parentheses
- leetcode 20. Valid Parentheses
- leetcode 20. Valid Parentheses
- LeetCode-20.Valid Parentheses
- LeetCode *** 20. Valid Parentheses
- LeetCode 20. Valid Parentheses
- leetcode-20. Valid Parentheses
- Bmob(wechatApp)--查询数据
- tar:归档中找不到 tar: 由于前次错误,将以上次的错误状态退出
- 编译ionic时出错:You have not accepted the license agreements of the following SDK components
- TortoiseGit还原文件到历史版本
- 安装android studio时候弹出unable to access android sdk add-on list解决方法
- 【LeetCode】20. Valid Parentheses
- Activity中各个方法的作用
- list-style-type的属性值
- mysql函数大全及演示
- java-正则表达式判断手机号
- TensorFlow运作方式入门
- 将 ext_net 连接到 router
- Bootstrap的模态框遮罩在iframe子页面弹出时不能覆盖父页面的解决方法
- cmsg(3) - Linux man page