leetcode--Valid Parentheses
2015-05-08 00:40
204 查看
Given a string containing just the characters
The brackets must close in the correct order,
public class Solution {
public boolean isValid(String s) {
if(s.length()==0) return true;
Stack<Character> stack = new Stack<Character>();
int i=0;
do{
char cur = s.charAt(i);
if(stack.size()!=0){
switch(cur){
case ']':
if(stack.peek()=='[') stack.pop();
else stack.add(cur);
break;
case '}':
if(stack.peek()=='{') stack.pop();
else stack.add(cur);
break;
case ')':
if(stack.peek()=='(') stack.pop();
else stack.add(cur);
break;
default:
stack.add(cur);
}
}else{
stack.add(cur);
}
i++;
}while(i!=s.length());
if(stack.size()==0) return true;
else return false;
}
}
'(',
')',
'{',
'}',
'['and
']', determine if the input string is valid.
The brackets must close in the correct order,
"()"and
"()[]{}"are all valid but
"(]"and
"([)]"are not.
public class Solution {
public boolean isValid(String s) {
if(s.length()==0) return true;
Stack<Character> stack = new Stack<Character>();
int i=0;
do{
char cur = s.charAt(i);
if(stack.size()!=0){
switch(cur){
case ']':
if(stack.peek()=='[') stack.pop();
else stack.add(cur);
break;
case '}':
if(stack.peek()=='{') stack.pop();
else stack.add(cur);
break;
case ')':
if(stack.peek()=='(') stack.pop();
else stack.add(cur);
break;
default:
stack.add(cur);
}
}else{
stack.add(cur);
}
i++;
}while(i!=s.length());
if(stack.size()==0) return true;
else return false;
}
}
相关文章推荐
- Leetcode: Valid Parentheses
- leetcode 20. Valid Parentheses
- Leetcode:Longest Valid Parentheses
- Leetcode -- 20. Valid Parentheses
- LeetCode_Longest Valid Parentheses
- [LeetCode]Valid Parentheses
- LeetCode 32. Longest Valid Parentheses
- LeetCode之Valid Parentheses
- leetcode-20Valid Parentheses
- LeetCode 20 Valid Parentheses (括号匹配问题)
- [LeetCode] Valid Parentheses
- leetcode: 20. Valid Parentheses
- LeetCode----20. Valid Parentheses
- 【Leetcode】Valid Parentheses in JAVA——一个括号de了20分钟bug的故事
- (LeetCode)Longest Valid Parentheses
- leetcode 20 Valid Parentheses 括号匹配
- [leetcode 20] Valid Parentheses
- leetcode 20. Valid Parentheses
- [LeetCode]20. Valid Parentheses