Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
从前到后遍历字符串中的字符,如果该字符是左括号('(','[','{')就依次存储;如果是右括号(')',']','}')就要与已保存的最近一次的字符进行比对,如果是同类型的括号(配成了一对),将其弹出,不再存储;如果既不是左括号又不是右括号,报错。遍历完字符串中的字符后,存储的字符数为空,返回true,否则false。
给出2种java solutions: 使用Stack(java.util.Stack),后进先出(last in first out)的堆栈
1. clearly understandable solution (a bit faster than the following one)
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for(int i = 0;i < s.length();i ++){
char c = s.charAt(i);
if(c == '(' || c== '[' || c== '{'){
stack.push(c);
}
else if(!stack.empty() && ((c == ')' && stack.peek() == '(') ||( c == ']' && stack.peek() == '[' ) || ( c == '}' && stack.peek() == '{'))){
stack.pop(); //before pop operation,test if the stack is empty or not is needed
}else{
return false;
}
}
return stack.empty();
}
}
2. a tricky solution, but a little slower:
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(char c:s.toCharArray()){//nice short for loop
if(c == '('){
stack.push(')'); //once got the left bracket, just save the same type of the right bracket
}else if(c == '['){
stack.push(']');
}else if(c == '{'){
stack.push('}');
}else if(stack.isEmpty()||stack.pop()!=c){ //if the stack is empty or popping the last-in character is not the right one,return false
return false;
}
}
return stack.isEmpty();
}
}