栈的典型题目还是比较明显的,括号匹配,表达式计算等等都离不开栈,本小节就针对两个经典的问题进行解析。
首先看题目要求,LeetCode 20.给定一个只包含'(',')','{','}','[',']' 的字符串 s,判断字符串是否有效。有效的字符串满足:
示例 1:
输入:s = "()" 输出:true
示例 2:
输入:s = "()[]{}" 输出:true
示例 3:
输入:s = "(]" 输出:false
本题比较麻烦的点在于如何判断两个符号是不是同一组得,我们可以将哈希表将所有的符号进行存储,左半边做 key,右半边做 value,遍历字符串的时候,遇到左半边的符号就入栈,遇到右半边的符号就和栈顶的符号比较,不匹配就返回 false(题目没有使用哈希表,因为我个人感觉直接匹配可能更快)
class Solution {
public boolean isValid(String s) {
if(s.length() <= 1){
return false;
}
Stack<Character> stack = new Stack<>();
for(int i = 0; i < s.length();i++){
char item = s.charAt(i);
if( item == '(' || item == '[' || item =='{'){
stack.push(item);
}else{
if(stack.size() == 0){
return false;
}
char left = stack.pop();
if((left == '{' && item == '}' )
|| (left == '[' && item == ']')
|| (left == '(' && item == ')')){
continue;
}else{
return false;
}
}
}
return stack.size() == 0;
}
}
LeetCode 给我们赵乐十几个括号匹配的问题,都是条件变去,但是解决起来有难有易,如果感兴趣的话可以继续研究一下:
LeetCode 155 ,设计一个支持push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
实现 MinStack 类:
示例 1:
输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
输出:
[null,null,null,null,-3,null,0,-2]
解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
本题的关键在于理解 getMin() 到底表示什么,可以看一个例子上面的示例画成示意图如下:
这里的关键在于理解对应的 Min 栈内,中间元素为什么是 -2 ,理解了本题就非常简单了。
题目要求在常数时间内获取栈的最小值,因此不能在 getMin ( )的时候再去计算最小值,最好应该在 push 或者 pop 的时候就已经计算机好了当前栈中的最小值。
对于栈来说,如果一个元素 a 在入栈的时候,栈里面有其他的元素 b,c,d,那么无论这个栈在之后经历了什么操作,只要在栈 a 中,b,c,d就一定在栈中,因为 a 被弹出之前,b,c,d 不会被弹出。
因此,在操作过程中的任意一个时刻,只要栈顶的元素是 a,那么我们就可以确定栈里面现在的元素一定是 a,b,c,d.那么,我们可以在每个元素 a 入栈的时候就把当前栈的最小值 m 存储起来,然后在这之后,无论什么时候,如果栈顶元素是 a,那么我们就可以返回最小值 m 。
按照上面的思路,我们只需要设计一个数据结构,使得每个元素 a 与其相应的最小值 m 时刻保持一一对应。因此我们可以使用一个辅助栈,与元素栈同步插入和删除,用于存储于每个元素对应的最小值。
在任意一个时刻,栈内元素的最小值就存储在辅助栈的栈顶元素中。
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();
}
}
在以上方法之后,我进行了一部分的改进,使用链栈实现最小栈查询,这样的话可以提高效率
class MinStack {
/**
* 私有化头结点
*/
private Node head;
public MinStack() {
}
/**
* '
* 入栈
*
* @param val 插入的值
*/
public void push(int val) {
if (head == null){
head = new Node(val,val,null);
return;
}
head = new Node(val,Math.min(val,head.min),head);
}
/**
* 出栈
*/
public void pop() {
head = head.next;
}
/**
* 查看栈顶元素
*
* @return
*/
public int top() {
return head.val;
}
/**
* 获取栈中元素最小值
*
* @return 最小值
*/
public int getMin() {
return head.min;
}
/**
* 构造化节点类,用于实现链栈
*/
private class Node {
private int val;
private int min;
private Node next;
public Node(int val, int min, Node next) {
this.val = val;
this.min = min;
this.next = next;
}
public Node(int val, int min) {
this(val, min, null);
}
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
LeetCode 716(力扣可能需要会员,可以上炼码 859 看看)
设计一个支持push,pop,top,peekMax和popMax操作的最大栈。
示例:
输入:
push(5)
push(1)
push(5)
top()
popMax()
top()
peekMax()
pop()
top()
输出:
5
5
1
5
1
5
这题与上一题相反,但是处理方法一致。一个普通的栈可以支持前三项操作:
所以我们仅仅需要考虑后两种操作就可以了,即 peekMax( ) 和 popMax( )。
对于 peekMax(),我们可以另一个栈来存储每个位置到栈底的所有元素的最大值。例如,如果当前第一个栈中的元素为 [2,1,5,3,9],那么第二个栈中的元素也为【2,2,5,5,9】。在 push(x)操作的时候,只需要将第二个栈的栈顶和 xx 的最大值入栈,而在 pop() 操作的时候,只需要将第二个栈进行出栈。
对于 popMax(),由于我们知道当前栈中最大的元素值,因此可以直接将两个栈同时出栈,并存储第一个栈出栈的所有值。当某个时刻,第一个栈的出栈元素等于当前栈中最大的元素值的时候,就找到最大的元素,此时我们将之前出第一个栈的所有元素重新入栈,并且同步更新第二个栈,就完成了 popMax 的操作。
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;
}
}
这里我使用了链栈进行改进,不过 popMax 方法是一样的,其他方法和最小栈差不了多少。
class MaxStack {
private Node head;
public MaxStack() {
// do intialization if necessary
}
/*
* @param number: An integer
* @return: nothing
*/
public void push(int val) {
// write your code here
if (head == null){
head = new Node(val,val,null);
return;
}
head = new Node(val,Math.max(val,head.max),head);
}
public int pop() {
// write your code here
int val = head.val;
head = head.next;
return val;
}
/*
* @return: An integer
*/
public int top() {
// write your code here
return head.val;
}
/*
* @return: An integer
*/
public int peekMax() {
// write your code here
return head.max;
}
/*
* @return: An integer
*/
public int popMax() {
// write your code here
int max = peekMax();
Stack<Integer> buffer = new Stack();
while(top() != max) buffer.push(pop());
pop();
while(!buffer.isEmpty()) push(buffer.pop());
return max;
}
/**
* 构造化节点类,用于实现链栈
*/
private class Node {
private int val;
private int max;
private Node next;
public Node(int val, int max, Node next) {
this.val = val;
this.max = max;
this.next = next;
}
public Node(int val, int max) {
this(val, max, null);
}
}
}
阅读量:965
点赞量:0
收藏量:0