括号问题
题目: leetcode20
public boolean isValid(String s) {
// 偶数直接不行啊
if (s.length() <= 1 || s.length() % 2 != 0) {
return false;
}
// 放入括号的各种关系
Map<Character, Character> smap = new HashMap<>();
smap.put('(', ')');
smap.put('{', '}');
smap.put('[', ']');
Stack<Character> stack = new Stack<>();
// 循环遍历 s 的每一个字符
for (int i = 0; i < s.length(); i++) {
// 获取当前对应的字符
char c = s.charAt(i);
// 如果 map 中包含这个字符那么可以直接添加进 stack 中
if (smap.containsKey(c)) {
// 添加到 stack 中的是对应的 smap 的 value 值
// 目的是方便于后面取出来方便进行比较
stack.push(smap.get(c));
} else {
// 首先要保证 stack 是否为 null 如果是空表示的是一种情况:就是只有单向括号,比如 )} ]
if (!stack.isEmpty()) {
// 这里已经到了一个特殊位置 比如 ([{}]) 比如索引为 3 的 } 的位置
// 到了这个位置,后面直接取出栈中的元素,取出来进行即可
char left = s.charAt(i);
// 取出栈中的元素
char right = stack.pop();
// 进行比较,如果不一致直接返回 false 即可
// 由于这里「栈」中存的就是 smap 的 vlue 值所以直接比较即可
if (left != right) {
return false;
}
} else {
// 如果只是含有 )} ],那么直接返回 false
return false;
}
}
}
// 这里还需要判断 stack 中是否为 null 如果是 null 那么需要直接返回 true
// 如果不是空,那么就表示 两边对应的数量不一致,直接返回 false
return stack.isEmpty();
}
最小栈
题目:155. 最小栈
这里的思想是比较重要的
首先
- 需要两个独立的
栈
- 需要同时出栈的一个栈的值 和
辅助栈
的最小值
插入时
具体代码
class MinStack {
Deque<Integer> xStack;
Deque<Integer> minStack;
public MinStack() {
xStack = new LinkedList<Integer>();
minStack = new LinkedList<Integer>();
// 放入一个初始化的值
minStack.push(Integer.MAX_VALUE);
}
public void push(int x) {
xStack.push(x);
// 比较插入的值和该栈中最小的值之间的关系
minStack.push(Math.min(minStack.peek(), x));
}
public void pop() {
xStack.pop();
minStack.pop();
}
public int top() {
return xStack.peek();
}
public int getMin() {
return minStack.peek();
}
}
最大栈
题目:LeetCode 716
class MaxStack {
Stack<Integer> stack;
Stack<Integer> maxStack;
public MaxStack() {
stack = new Stack();
maxStack = new Stack();
}
public void push(int x) {
int max = maxStack.isEmpty() ? x : maxStack.peek();
maxStack.push(max > x ? max : x);
stack.push(x);
}
public int pop() {
maxStack.pop();
return stack.pop();
}
public int top() {
return stack.peek();
}
public int peekMax() {
return maxStack.peek();
}
public int popMax() {
int max = peekMax();
Stack<Integer> buffer = new Stack();
while (top() != max) {
buffer.push(pop());
}
pop();
while (!buffer.isEmpty()) {
push(buffer.pop());
}
return max;
}
}