栈的括号、最小、最大问题

括号匹配问题

leetcode20:给定一个只包括'(',')','[',']','{','}',的字符串s,判断字符串是否有效。

左括号必须要以相同类型的右括号闭合。

(){}[]

{[()]}

使用map来记录key(左括号)和value(右括号),遇到左括号就入栈,遇到右括号就与栈顶元素比较,不匹配则return false。

    public static boolean isValid(String s){
        if (s.length()<=1){
            return false;
        }
        Map<Character,Character> smap = new HashMap<>();
        smap.put('(',')');
        smap.put('[',']');
        smap.put('{','}');
        Stack<Character> stack = new Stack<>();
        for (int i = 0;i<s.length();i++){
            char item = s.charAt(i);
            if (smap.containsKey(item)){
                stack.push(item);
            }else {
                if (!stack.isEmpty()){
                    Character left = stack.pop();
                    char right = smap.get(item);
                    if (right!=left){
                        return false;
                    }
                }else {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

最小栈

使用辅助栈minStack,在进行stack.push(x)操作时,将x与minStack的peek()进行比较,minStack.push(x>minStack.peek()?minStack.peek():x),可以在初始化时minStack.push(Integer.MAX_VLAUE),或者在每次push()时判断stack是否isEmpty(),没有则直接minStack.push(x),否则进行判断。

import java.util.Deque;
import java.util.LinkedList;

public 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 int pop(){
        minStack.pop();
        return xStack.pop();
    }
    public int top(){
        return xStack.peek();
    }
    public int getMin(){
        return minStack.peek();
    }
}

最大栈

基本同上

public 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);
        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()){
            stack.push(buffer.pop());
        }
        return max;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值