LeetCode 20. 有效的括号
20. 有效的括号
Solution
思路:左边入栈,遇到右边判断即可,最后看堆栈是否为空。
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
char[] str = s.toCharArray();
int len = s.length();
for (int i = 0; i < len; i++) {
if (str[i] == '(' || str[i] == '[' || str[i] == '{') {
stack.push(str[i]);
} else {
if (stack.empty()) return false;
char ch = stack.peek();
if (str[i] == ')') {
if (ch != '(') return false;
} else if (str[i] == ']') {
if (ch != '[') return false;
} else {
if (ch != '{') return false;
}
stack.pop();
}
}
if (stack.empty()) return true;
else return false;
}
}
不过Stack
类不推荐使用,可以使用Deque
实现类ArrayDeque
和LinkedList
的区别:
ArrayDeque
数组实现,随机存取效率高,队列、栈的效率好一点,循环数组的删除不涉及元素的移动
LinkedList
插入、删除的优势更大
class Solution {
public boolean isValid(String s) {
Map<Character, Character> map = new HashMap<>();
map.put(')', '(');
map.put(']', '[');
map.put('}', '{');
Deque<Character> deque = new ArrayDeque<>();
int len = s.length();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (map.containsKey(c)) {
if (deque.size() == 0 || deque.peek() != map.get(c)) {
return false;
}
deque.pop();
} else {
deque.push(c);
}
}
if (deque.size() == 0) {
return true;
} else {
return false;
}
}
}
埋骨何须桑梓地,人生无处不青山