普通栈
LeetCode20 有效的括号
LeetCode20 有效的括号
定义一个辅助map,判断字符串的字符是否在
]})
中。一旦是右括号就要弹出元素,判断匹配。
class Solution {
public boolean isValid(String s) {
if (s.length() % 2 == 1) {
return false;
}
Map<Character, Character> pairs = new HashMap<>();
pairs.put(')', '(');
pairs.put(']', '[');
pairs.put('}', '{');
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (pairs.containsKey(s.charAt(i))) {
if (stack.isEmpty() || pairs.get(s.charAt(i)) != stack.peek()) {
return false;
}
stack.pop();
} else {
stack.push(s.charAt(i));
}
}
if (!stack.isEmpty()) {
return false;
}
return true;
}
}
LeetCode155. 最小栈
LeetCode155. 最小栈
使用栈记录最小的元素。
class MinStack {
private Stack<Integer> stack;
private Stack<Integer> minStack;
public MinStack() {
stack = new Stack<>();
minStack = new Stack<>();
}
public void push(int val) {
stack.push(val);
if (minStack.isEmpty() || minStack.peek() >= val) {
minStack.push(val);
}
}
public void pop() {
Integer pop = stack.pop();
if (pop.equals(minStack.peek())) {
minStack.pop();
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}
LeetCode232. 用栈实现队列
LeetCode232. 用栈实现队列