代码随想录打卡第10天

232 用队列实现栈

image

两个栈一个负责入一个负责出。

class MyQueue {
    Stack<Integer> stackIn;
    Stack<Integer> stackOut;

    public MyQueue() {
        stackIn=new Stack<>();
        stackOut= new Stack<>();
    }
    
    public void push(int x) {
        stackIn.push(x);
    }
    
    public int pop() {
        moveStackIn();
        return stackOut.pop();
    }
    
    public int peek() {
        moveStackIn();
        return stackOut.peek();
    }
    
    public boolean empty() {
        return stackIn.isEmpty() && stackOut.isEmpty();
    }
    public void moveStackIn(){
        if(!stackOut.isEmpty()) return;
        while(!stackIn.isEmpty()){
            stackOut.push(stackIn.pop());
        }
    }
}

225 用队列实现栈

使用两个队列,第二个队列充当的是备份的作用

class MyStack {
    // q1作为主要的队列,其元素排列顺序和出栈顺序相同
    Queue<Integer> que1 = new ArrayDeque<>();
    // q2仅作为临时放置
    Queue<Integer> que2 = new ArrayDeque<>();

    public MyStack() {

    }

    public void push(int x) {
        while (que1.size() > 0) {
            que2.add(que1.poll());
        }
        que1.add(x);
        while (que2.size() > 0) {
            que1.add(que2.poll());
        }
    }

    public int pop() {
        return que1.poll();
    }

    public int top() {
        return que1.peek();
    }

    public boolean empty() {
        return que1.isEmpty();
    }
}

20 有效的括号

栈的经典题,要想好不匹配的情况
image

先将与左边匹配的右边括号放入栈中,如果遇到右边括号,则对比栈顶是否相同,如果相同则弹出,如果不同则返回false

class Solution {
    public boolean isValid(String s) {
        Deque<Character> que= new LinkedList<>();
        char ch;
        for(int i=0;i<s.length();i++){
            ch=s.charAt(i);
            if(ch=='('){
                que.push(')');
            }else if(ch=='['){
                que.push(']');
            }else if(ch=='{'){
                que.push('}');
            }else if(que.isEmpty()||ch!=que.peek()){
                return false;
            }else{
                que.pop();
            }
        }
        return que.isEmpty();
    }
}

1047 删除字符串中重复的元素

注意栈是用来存放的,还有p拼接字符串的字符顺序

class Solution {
    public String removeDuplicates(String s) {
        // ArrayDeque会比LinkedList在除了删除元素这一点外会快一点
        ArrayDeque<Character> que = new ArrayDeque<>();
        char ch;
        for (int i = 0; i < s.length(); i++) {
            ch = s.charAt(i);
            if (que.isEmpty() || ch != que.peek()) {
                que.push(ch);
            } else {
                que.pop();
            }
        }
        String res = "";
        while (!que.isEmpty()) {
            res = que.pop()+res;//注意顺序
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

endless_?

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值