20. Valid Parentheses
来源:互联网 发布:572-393的简便算法 编辑:程序博客网 时间:2024/06/05 10:23
问题描述:
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.
第一次遇到字符匹配的问题,完全不知从何入手啊~想了半天没思路然后参考了一般别人的答案突然灵光一现:类似“{({})}”,“{()}”都是轴对称图形啊!那就用堆栈存序列:当遇到“(”存“)”、遇到{存}遇到【存】,最后判断生成的堆栈里面的字符串和原来的是否相同就行了呀!然而。。。。图森破!!eg: “{}【】()”这也不是轴对称啊。。。跪了,但是,我的方法可以用来验证是否轴对称哇~~嘻嘻,记录在这里~
public static boolean isValid(String s) {//判断是否轴对称 Stack<Character> res = new Stack<Character>(); String gene = ""; for(char c:s.toCharArray()){ if(c=='(') res.push(')'); if(c==')') res.push('('); if(c=='{') res.push('}'); if(c=='}') res.push('{'); if(c=='[') res.push(']'); if(c==']') res.push('['); } boolean flag = true; while(flag){ char thispop = res.pop(); gene = gene + String.valueOf(thispop); if(res.isEmpty()) flag = false; } if(gene.equals(s)) return true; return false; }
然后跪了之后,继续看答案的我。。。。明白了别人的真实意图:只有遇到“(”、“{”、“【”的时候才压栈其对应另一半,然后遇到“}”、“】”、“)”的时候就弹栈。也就是说,堆栈里面存的是还没找到另一半的符号的 应该有的另一半啊(看看人家多机智,都知道自己喜欢啥样的哈哈哈) 由于堆栈先进后出的特点就可以保证符号的顺序性了~~机智!!
class Solution { public static boolean isValid(String s) { Stack<Character> res = new Stack<Character>(); for(char c:s.toCharArray()){ if(c=='(') res.push(')'); else if(c=='{') res.push('}'); else if(c=='[') res.push(']'); else if(res.isEmpty()||res.pop()!=c) return false; } return res.isEmpty(); }}
阅读全文
1 0
- LeetCode 20. Valid Parentheses
- [LeetCode] 20.Valid Parentheses
- LeetCode --- 20. Valid Parentheses
- LeetCode 20.Valid Parentheses
- [Leetcode] 20. Valid Parentheses
- 20.Valid Parentheses
- 20.Valid Parentheses
- 20. Valid Parentheses
- 【leetcode】20. Valid Parentheses
- [leetcode] 20.Valid Parentheses
- [leetcode] 20. Valid Parentheses
- 20. Valid Parentheses
- 20. Valid Parentheses
- 20. Valid Parentheses
- Leetcode 20. Valid Parentheses
- 20. Valid Parentheses LeetCode
- 20. Valid Parentheses
- 20. Valid Parentheses
- 初识JWT(java web token)
- PyCharm配置mongo插件
- Java垃圾回收机制(2)- Java的内存分布
- 视频检测之:利用结构稀疏性(结构稀疏范数)进行RPCA分析
- bzoj4996: [Usaco2017 Feb]Why Did the Cow Cross the Road II
- 20. Valid Parentheses
- Ubuntu & GitLab CI & Docker & ASP.NET Core 2.0 自动化发布和部署(1)
- 关于Thinkpad E540 电脑更换固态硬盘的相关问题
- BZOJ[3038]上帝造题的7分钟2 树状数组+并查集
- KMP算法详解
- Accelerated C++ 15 Revisiting character pictures
- Java入门(7)——循环和debug 调试
- JDBC批量插入数据优化,使用addBatch和executeBatch
- 系统学习C++(1)