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是否为空,若空则false,若不空则pop出一个character并检查是否与当前character匹配。最后全部检查完,看stack是否为空,若空则匹配完全,若不为空证明还有符号未匹配,return false。
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;
}
}