【leetcode】第五章 栈与队列part02

232.用栈实现队列

  • 用两个栈来实现
  • 当pop时,检测out栈是否为空,若为空,则将in栈的元素全都放入out栈中
java 复制代码
class MyQueue {

    private Stack<Integer> in;
    private Stack<Integer> out;

    public MyQueue() {
        in = new Stack<>();
        out = new Stack<>();
    }

    public void push(int x) {
        in.push(x);
    }

    public int pop() {

        if (out.isEmpty()) {
            while (!in.isEmpty()) {
                out.push(in.pop());
            }
        }
        return out.pop();
    }

    public int peek() {
        if (out.isEmpty()) {
            while (!in.isEmpty()) {
                out.push(in.pop());
            }
        }
        return out.peek();
    }

    public boolean empty() {
        return in.isEmpty() && out.isEmpty();
    }
}

225. 用队列实现栈

  • 单个队列方法
  • 将前面n-1个元素弹出并加入底部,这样就可以模拟后进先出
java 复制代码
class MyStack {
    // 用单个队列
    // 将前面n-1个元素弹出并加入底部
    private Queue<Integer> a;

    public MyStack() {
        a = new LinkedList<>();
    }
    
    public void push(int x) {
        // size-1
        int n = a.size();
        a.offer(x);
        while (n > 0) {
            a.offer(a.poll());
            n--;
        }
    }
    
    public int pop() {
        return a.poll();
    }
    
    public int top() {
        return a.peek();
    }
    
    public boolean empty() {
        return a.isEmpty();
    }
}

20. 有效的括号

java 复制代码
public boolean isValid(String s) {
    // 输入:s = "()[]{}"
    //输出:true
    HashMap<Character,Character> map = new HashMap<>();
    map.put('(',')');
    map.put('[',']');
    map.put('{','}');

    Stack<Character> stack = new Stack<>();
    for (int i = 0; i < s.length(); i++) {
        char ch = s.charAt(i);
        if (ch == '(' || ch == '{' || ch == '[') {
            stack.push(map.get(ch));
        }
        // [()]
        // ])
        else if (stack.isEmpty() || ch != stack.pop()) {
            return false;
        }
    }
    // ([
    return stack.isEmpty();
}
  • Deque和Stack
java 复制代码
public boolean isValid(String s) {
    // 输入:s = "()[]{}"
    //输出:true
    HashMap<Character,Character> map = new HashMap<>();
    map.put('(',')');
    map.put('[',']');
    map.put('{','}');

    Deque<Character> stack = new LinkedList<>();
    for (int i = 0; i < s.length(); i++) {
        char ch = s.charAt(i);
        if (ch == '(' || ch == '{' || ch == '[') {
            stack.push(map.get(ch));
        }
        // [()]
        // ])
        else if (stack.isEmpty() || ch != stack.pop()) {
            return false;
        }
    }
    // ([
    return stack.isEmpty();
}

1047. 删除字符串中的所有相邻重复项

  • 要知道栈为什么适合做这种类似于爱消除的操作,因为栈帮助我们记录了 遍历数组当前元素时候,前一个元素是什么
java 复制代码
public String removeDuplicates(String s) {
    // 输入:"abbaca"
    //输出:"ca"
    Deque<Character> stack = new LinkedList<>();
    for (int i = 0; i < s.length(); i++) {
        char ch = s.charAt(i);
        if (stack.isEmpty()) {
            stack.push(ch);
            continue;
        } else if (ch == stack.peek()) {
            stack.pop();
            continue;
        }
        stack.push(ch);

    }
    StringBuilder sb = new StringBuilder();
    while (!stack.isEmpty()) {
        sb.append(stack.pop());
    }
    return sb.reverse().toString();
}

150. 逆波兰表达式求值

java 复制代码
public static int evalRPN(String[] tokens) {
    Deque<Integer> stack = new LinkedList<>();
    for (String token : tokens) {

        switch (token){
            case "+":
                stack.push(stack.pop()+stack.pop());
                break;
            case "-":
                stack.push(-1*(stack.pop()-stack.pop()));
                break;
            case "*":
                stack.push(stack.pop()*stack.pop());
                break;
            case "/":
                int a = stack.pop();
                int b = stack.pop();
                stack.push(b/a);
                break;
            default:
                stack.push(Integer.parseInt(token));
        }

    }
    return stack.pop();
}
相关推荐
格图素书43 分钟前
数学建模算法案例精讲500篇-【数学建模】DBSCAN聚类算法
算法·数据挖掘·聚类
DashVector2 小时前
向量检索服务 DashVector产品计费
数据库·数据仓库·人工智能·算法·向量检索
AI纪元故事会2 小时前
【计算机视觉目标检测算法对比:R-CNN、YOLO与SSD全面解析】
人工智能·算法·目标检测·计算机视觉
夏鹏今天学习了吗2 小时前
【LeetCode热题100(59/100)】分割回文串
算法·leetcode·深度优先
卡提西亚2 小时前
C++笔记-10-循环语句
c++·笔记·算法
还是码字踏实2 小时前
基础数据结构之数组的双指针技巧之对撞指针(两端向中间):三数之和(LeetCode 15 中等题)
数据结构·算法·leetcode·双指针·对撞指针
Coovally AI模型快速验证4 小时前
当视觉语言模型接收到相互矛盾的信息时,它会相信哪个信号?
人工智能·深度学习·算法·机器学习·目标跟踪·语言模型
电院工程师5 小时前
SIMON64/128算法Verilog流水线实现(附Python实现)
python·嵌入式硬件·算法·密码学
轮到我狗叫了5 小时前
力扣.84柱状图中最大矩形 力扣.134加油站牛客.abb(hard 动态规划+哈希表)牛客.哈夫曼编码
算法·leetcode·职场和发展
丛雨要玩游戏5 小时前
字符函数和字符串函数
c语言·开发语言·算法