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.
采用堆栈进行符号匹配。
需要注意的是当进行peek和pop操作时候需要首先判断堆栈是否为空,否则会抛出StackEmptyException。
public boolean isValid(String s) {
Stack<String> sta = new Stack<String>();
for(int i = 0;i<s.length();i++){
if(s.charAt(i)=='('||s.charAt(i)=='{'||s.charAt(i)=='['){
sta.push(s.charAt(i)+"");
}else if(sta.isEmpty()){
return false;
}
else if(!sta.isEmpty()){
if(s.charAt(i)==')'&&sta.peek().equals("(")
||s.charAt(i)=='}'&&sta.peek().equals("{")
||s.charAt(i)==']'&&sta.peek().equals("[")){
sta.pop();
}else{
return false;
}
}
}
return sta.isEmpty();
}
下回堆栈类型直接用char型就可以了,不用String转换成char了