题目:
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
代码:
public static boolean isValid(String s) {
Stack<Character> stack=new Stack<Character>();
Hashtable<Character, Character> hashtable=new Hashtable<>();
hashtable.put('(', ')');
hashtable.put('{', '}');
hashtable.put('[', ']');
char[] input=s.toCharArray();
for(int i=input.length-1;i>=0;i--)
{
if(input[i]==')'||input[i]=='}'||input[i]==']')
{
stack.push(input[i]);
}
else {
Character temp=null;
if(stack.empty())
return false;
else {
temp=stack.pop();
}
if(hashtable.get(input[i])!=temp)
return false;
}
}
if(stack.empty())
return true;
else {
return false;
}
}