题目:
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),并判断两者是否匹配,若不匹配,则返回false;直到遍历结束,此时,若栈空,返回true,否则false。
程序:
class Solution {
public boolean isValid(String s) {
Stack stack = new Stack();
for(int i = 0; i < s.length(); i ++){
if( s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{')
stack.push(s.charAt(i));
else{
if(stack.empty())
return false;
char c = (char)stack.pop();
char match;
if(s.charAt(i)==')')
match = '(';
else if(s.charAt(i)==']')
match = '[';
else
match = '{';
if(match != c)
return false;
}
}
if(!stack.empty())
return false;
return true;
}
}