自己写的是纯用栈写的,只判断是不是右括号,可以直接抵消的话继续进行,否则就匹配不上,左括号直接进,最后返回栈是否为空。
public boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (stack.isEmpty()) stack.addLast(c);
else {
if (c == ')') {
if (stack.peekLast() == '(') stack.pollLast();
else return false;
} else if (c == '}') {
if (stack.peekLast() == '{') stack.pollLast();
else return false;
} else if (c == ']') {
if (stack.peekLast() == '[') stack.pollLast();
else return false;
} else {
stack.addLast(c);
}
}
}
return stack.isEmpty();
}
代码优化的话可以用map实现不用那么多判断
private static final Map<Character,Character> map = new HashMap<Character,Character>(){{
put('{','}'); put('[',']'); put('(',')'); put('?','?');
}};
public boolean isValid(String s) {
if(s.length() > 0 && !map.containsKey(s.charAt(0))) return false;
LinkedList<Character> stack = new LinkedList<Character>() {{ add('?'); }};
for(Character c : s.toCharArray()){
if(map.containsKey(c)) stack.addLast(c);
else if(map.get(stack.removeLast()) != c) return false;
}
return stack.size() == 1;
}