原题:(频率5)
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.
题意:就是判断括号是否对称
代码和思路:
很简单,用一个栈,碰到open括号,就把close括号加入栈。遇到close括号,就弹出栈顶元素,看是否相等。
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(char c : s.toCharArray()){
if(c=='('){
stack.push(')');
}
else if(c=='['){
stack.push(']');
}
else if(c=='{'){
stack.push('}');
}
else if(stack.isEmpty() || stack.pop()!=c){
return false;
}
}
return stack.isEmpty();
}
}