心血来潮,半夜做了一道Lintcode的题目,调试完睡觉,欢迎大家批评指正。
public boolean isValidParentheses(String s) {
// Write your code here
Stack stack=new Stack();
if(s.length()==0){
return true;
}else if(s.length()==1){
return false;
}
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='('||s.charAt(i)=='['||s.charAt(i)=='{'){
stack.add(s.charAt(i));
}else if(s.charAt(i)==')'){
if(!stack.isEmpty()&&stack.peek().equals('(')){
stack.pop();
}else{
return false;
}
}else if(s.charAt(i)==']'){
if(!stack.isEmpty()&&stack.peek().equals('[')){
stack.pop();
}else{
return false;
}
}else if(s.charAt(i)=='}'){
if(!stack.isEmpty()&&stack.peek().equals('{')){
stack.pop();
}else{
return false;
}
}
}
return stack.isEmpty();
}