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.
public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
int i=0;
while(i<s.length())
{
switch (s.charAt(i))
{
case '(':
case '[':
case '{':
stack.push(s.charAt(i));
break;
case ')':if(!stack.empty()&&stack.peek()=='(') stack.pop();
else stack.push(s.charAt(i));
break;
case ']':if(!stack.empty()&&stack.peek()=='[') stack.pop();
else stack.push(s.charAt(i));
break;
case '}':if(!stack.empty()&&stack.peek()=='{') stack.pop();
else stack.push(s.charAt(i));
break;
}
i++;
}
if(stack.empty())
return true;
else
return false;
}
}
后三种情况需要判断是否为空,如果直接判断stack.peek(),会报空异常。