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){
int len = s.length();
if(len <= 1)
return false;
if(s.charAt(0) == ')' || s.charAt(0)==']' || s.charAt(0)=='}')
return false;
Stack<Character> stack = new Stack<Character>();
for(int i=0;i<len;i++){
if(s.charAt(i) == '(' || s.charAt(i)=='[' || s.charAt(i)=='{')
stack.push(s.charAt(i));
else{
if(stack.size() == 0)
return false;
if(s.charAt(i) == ')')
if(stack.peek() != '(')
return false;
if(s.charAt(i) == ']')
if(stack.peek() != '[')
return false;
if(s.charAt(i) == '}')
if(stack.peek() != '{')
return false;
stack.pop();
}
}
return stack.size() == 0;
}