*Valid Parentheses
2015-09-16 05:26
253 查看
题目:
Given a string containing just the characters
The brackets must close in the correct order,
题解:
这道题是一道很常见的老题,记得当时看严蔚敏的数据结构还有数据结构课上面都见过这道题,一道训练栈的基础题。
解题方法是:
一个个检查给的characters,如果是左括号都入栈;如果是右括号,检查栈如果为空,证明不能匹配,如果栈不空,弹出top,与当前扫描的括号检查是否匹配。
全部字符都检查完了以后,判断栈是否为空,空则正确都匹配,不空则证明有没匹配的。
注意:
检查字符是用==,检查String是用.isEqual(),因为String是引用类型,值相等但是地址可能不等。
代码如下:
reference: http://www.cnblogs.com/springfor/p/3869420.html
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.
题解:
这道题是一道很常见的老题,记得当时看严蔚敏的数据结构还有数据结构课上面都见过这道题,一道训练栈的基础题。
解题方法是:
一个个检查给的characters,如果是左括号都入栈;如果是右括号,检查栈如果为空,证明不能匹配,如果栈不空,弹出top,与当前扫描的括号检查是否匹配。
全部字符都检查完了以后,判断栈是否为空,空则正确都匹配,不空则证明有没匹配的。
注意:
检查字符是用==,检查String是用.isEqual(),因为String是引用类型,值相等但是地址可能不等。
代码如下:
public boolean isValid(String s) { if(s.length()==0||s.length()==1) return false; Stack<Character> x = new Stack<Character>(); for(int i=0;i<s.length();i++){ if(s.charAt(i)=='('||s.charAt(i)=='{'||s.charAt(i)=='['){ x.push(s.charAt(i)); }else{ if(x.size()==0) return false; char top = x.pop(); if(s.charAt(i)==')') if(top!='(') return false; else if(s.charAt(i)=='}') if(top!='{') return false; else if(s.charAt(i)==']') if(top!='[') return false; } } return x.size()==0; }
reference: http://www.cnblogs.com/springfor/p/3869420.html
相关文章推荐
- *Sqrt(x)
- 多核心Linux内核路径优化的不二法门之-slab与伙伴系统
- 多核心Linux内核路径优化的不二法门之-slab与伙伴系统
- LeetCode-Power of Two
- LeetCode-Ugly Number
- String to Integer (atoi)
- *LeetCode-Happy Number
- 深度学习word2vec笔记之算法篇
- SWERC2014 PRO A
- 优化PLM-ERP集成来满足动态的企业信息集成需求
- Citirx reciever 客户端添加帐户
- LeetCode-Reverse Linked List
- [Angular 2] 9. Replace ng-modle with #ref & events
- iOS疯狂详解之SQlite数据库增删改查
- [LeetCode#277] Find the Celebrity
- 面向对象(继承-概述2)
- Rearrange int array to put odd number to left and even to right
- 如何通过PLM和PLM-ERP集成来辅助管理复杂性
- Java + myBatis + MySql
- 程序上面,一般不使用 悲观锁