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.
思路: 括号匹配很简单,数据结构中教过大家使用栈来对括号进行匹配,左括号压栈,有对应的右括号出栈,否则返回false,最终的栈中为空即返回true,否则返回false。
public class Solution {
public boolean isValid(String s) {
Deque<Character> deque = new LinkedList<>();
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if ((c == '(') || (c == '[') || (c == '{'))
deque.addFirst(c);
else {
if (deque.isEmpty()) return false;
if (c == ')' && deque.getFirst() != '(' ||
c == ']' && deque.getFirst() != '[' ||
c == '}' && deque.getFirst() != '{')
return false;
deque.removeFirst();
}
}
return deque.isEmpty();
}
}