给定一个只含小中大括号的字符串, 判断这个字符串的括号是否都是成对一起的.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
Map<Character, Character> map = new HashMap<>();
map.put('(', ')');
map.put('{', '}');
map.put('[', ']');
for (int i = 0; i < s.length(); i++) {
char currentChar = s.charAt(i);
if (map.containsKey(currentChar)) {
stack.push(currentChar);
} else if (stack.isEmpty() || map.get(stack.pop()) != currentChar) {
return false;
}
}
return stack.isEmpty();
}
}

这个也没什么好说的, 就是如果要抵消左括号, 那右括号必须挨着才能抵消. 像是这种情况: ({)}是不行的.
时间复杂度: O(n)
空间复杂度: O(n)
n是字符串的长度