题:
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
#思路
利用栈特性 FILO 添加’(’ 、’{’ 、’[‘栈中放入(push入栈) ‘)’ 、’}’、’]’
遇到 ‘)’ 、’}’、’]’ 就出栈 (pop出栈)
代码
public boolean isValid(String s){
if(s.length() == 0){
return true;
}
Stack<Character> stack = new Stack<Character>();
for(Character c : s.toCharArray){
if(c == '('){
stack.push(')');
}
else if(c == '{'){
stack.push('}');
}
else if(c == '['){
stack.push(']');
}
else if(stack.empty() || c!=stack.pop()){
return false;
}
}
if(stack.empty()){
return true;
}
return false;
}