题目:
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.
运用stack。当输入是各种左括号时,push。当输入是各种右括号时,将pop出来的char和输入对比, 看能不能配对。
注意string循环完之后,stack得为空,才能返回true。
public class Solution {
private Stack<Character> stack = new Stack<Character>();
public boolean isValid(String s) {
char[] cList = s.toCharArray();
for(int i=0;i<cList.length;i++){
char c = cList[i];
if(c=='(' || c=='{' || c=='['){
stack.push(c);
}else{
if(stack.size() ==0){
return false;
}
if(c==')'){
char t = stack.pop();
if(t!='('){
return false;
}
}
else if(c==']'){
char t = stack.pop();
if(t!='['){
return false;
}
}
else if(c=='}'){
char t = stack.pop();
if(t!='{'){
return false;
}
}
}
}
if(stack.size() ==0){
return true;
}else{
return false;
}
}
}