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.
分析:
用stack解决,一个一个检查character,如果是左括号就放入stack;如果是右括号,看stack是否为空,若为空则不匹配,若不为空,判断pop出的是否匹配。全部检查完后,看stack是否为空,若空则valid,若不空证明还有没有匹配的所以不valid。
code:
public class Solution {
public boolean isValid(String s) {
if (s.length() == 0 || s.length() == 1) {
return false;
}
Stack<Character> stack = new Stack<Character>();
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.size() == 0) {
return false;
}
char top = stack.pop();
if (s.charAt(i) == ')') {
if (top != '(') {
return false;
}
} else if (s.charAt(i) == '}') {
if (top != '{') {
return false;
}
} else if (s.charAt(i) == ']'){
if (top != '[') {
return false;
}
}
}
}
return stack.size() == 0;
}
}