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.
Solution:
public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
char[] array = s.toCharArray();
if (array.length % 2 != 0) {
return false;
}
for(int i =0;i<array.length;i++){
char c = array[i];
if(c=='(' || c=='[' || c=='{'){
stack.push(c);
continue;
}
if(stack.isEmpty()==true){
return false;
}
if(c==')'){
if (stack.pop()!='(')
return false;
}else if(c==']'){
if(stack.pop()!='[')
return false;
}else if(c=='}'){
if(stack.pop()!='{')
return false;
}else{
return false;
}
}
if(stack.isEmpty()==false){
return false;
}else{
return true;
}
}
}
沒有留言:
張貼留言