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.
【算法思路】
用栈。
public boolean isValid(String s) {
int length = s.length();
if(length % 2 == 1)
{
return false;
}
HashMap<Character, Character> map = new HashMap<Character, Character>();
map.put('(', ')');
map.put('{', '}');
map.put('[', ']');
Stack<Character> stack = new Stack<Character>();
if(map.containsKey(s.charAt(0)))
stack.push(s.charAt(0));
else
return false;
for(int i = 1; i < length; i ++)
{
char ch = s.charAt(i);
if(!stack.isEmpty() && (map.get(stack.peek()) == ch))
{
stack.pop();
}
else if(map.containsKey(ch))
stack.push(ch);
else return false;
if(!stack.isEmpty() && (stack.size() > length - i))
return false;
}
return stack.isEmpty();
}