LeetCode:Valid Parentheses
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.
一开始把题目想的太简单,不知道({})这种包含括号的存在。
其实这道题很简单,用栈就可以解决。把遇到的字符压入栈,但新的字符与栈顶元素配对就弹出栈顶,不匹配就把新字符压入栈,这样最后看栈是否为空来判断input string is valid。
public class Solution {
public boolean isValid(String s) {
HashMap<Character,Character> map = new HashMap<Character,Character>();
boolean result = true;
if(s.length() == 0)return true;
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
map.put(']', '#');
map.put(')', '#');
map.put('}', '#');
char[] ch = s.toCharArray();
Stack<Character> stack = new Stack<Character>();
stack.push(ch[0]);
int i = 1;
while(i<ch.length)
{
char key = ch[i];
if(!stack.empty()&&map.get(stack.peek())==key)
{
stack.pop();
}
else
{
stack.push(ch[i]);
}
i++;
}
result = stack.empty();
return result;
}
}