问题:
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.
括号必须以正确的顺序关闭,“()”和“()[] {}”全部有效,但“(]”和“([)]”不是。
思路:
依次读取字符串,用栈存入括号的前半部分,也就是:'(','[','{'。若遇到括号的后半部分,检查栈顶的括号是否与此时的括号相匹配,若匹配则让栈顶元素出栈,再进行匹配下一组,直到栈为空。一旦遇到不匹配的情况,就返回False.
代码:
public boolean isValid(String s){
Stack<Character> stack = new Stack<Character>();
for(int i = 0;i<s.length();i++){
char ch = s.charAt(i);
if(ch == '(' || ch == '[' || ch == '{'){
stack.push(ch);
}
if(ch == ')' && (stack.isEmpty() || stack.pop()!='(')){
return false;
}
if(ch == ']' && (stack.isEmpty() || stack.pop()!='[')){
return false;
}
if(ch == '}' && (stack.isEmpty() || stack.pop()!='{')){
return false;
}
}
if(!stack.empty()){
return false;
}
return true;
}