代码随想录算法训练营Day10 | 232.用栈实现队列 225. 用队列实现栈 20. 有效的括号 1047. 删除字符串中的所有相邻重复项

Day10

这两天比较忙,好在栈相对简单

232. Implement Queue using Stacks

class MyQueue {
public:
    stack<int> in;
    stack<int> out;
    MyQueue() {

    }
    
    void push(int x) {
        in.push(x);
    }
    
    int pop() {
        if(!out.empty()){
            int val = out.top();
            out.pop();
            return val;
        }
        while(!in.empty()){
            out.push(in.top());
            in.pop();
        }
        int val = out.top();
        out.pop();
        return val;
    }
    
    int peek() {
        if(!out.empty()){
            return out.top();
        }
        while(!in.empty()){
            out.push(in.top());
            in.pop();
        }
        return out.top();
    }
    
    bool empty() {
        return in.empty() && out.empty();
    }
};

225. Implement Stack using Queues

class MyStack {
public:
    queue<int> q;
    MyStack() {

    }
    
    void push(int x) {
        q.push(x);
    }
    
    int pop() {
        int size = q.size();
        for(int i=0; i<size-1; ++i) {
            q.push(q.front());
            q.pop();
        }
        int val = q.front();
        q.pop();
        return val;
    }
    
    int top() {
        return q.back();
    }
    
    bool empty() {
        return q.size() == 0;
    }
};

20. Valid Parentheses

class Solution {
public:
    bool isValid(string str) {
        stack<char> s;
        for(int i=0; i<str.length(); ++i) {
            if(str[i] == '(' || str[i] == '[' || str[i] == '{') {
                s.push(str[i]);
            }
            else {
                if(!s.empty()) {
                    if(str[i] == ')' && s.top() != '(')
                        return false;
                    else if(str[i] == ']' && s.top() != '[')
                        return false;
                    else if(str[i] == '}' && s.top() != '{')
                        return false;
                    else {
                        s.pop();
                    }
                }
                else {
                    return false;
                }
            }
        }

        return s.empty();
    }
};

1047. Remove All Adjacent Duplicates In String

class Solution {
public:
    string removeDuplicates(string s) {
        stack<char> st;
        for(auto c : s)
        {
            if(st.empty() || st.top() != c)
                st.push(c);
            else if(st.top() == c)
                st.pop();
        }
        string ans = "";
        while(!st.empty())
        {
            ans = st.top() + ans;
            st.pop();
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值