7月13日-周四

一、刷题

1、力扣1047,删除字符串中的所有相邻项

遍历字符串,如果栈顶元素和遍历到的元素不同则压栈,相同则弹栈

整体代码

class Solution {
public:
    string removeDuplicates(string s) {
        stack<char> st;
        string res;

        for (int i = 0; i < s.size(); i++) {
            if (!st.empty() && st.top() == s[i]) st.pop();
            else st.push(s[i]);
        }
        while (!st.empty()) {
            res += st.top();
            st.pop();
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

2、力扣20,有效的括号

遍历字符串,将左括号变为右括号压栈(相较于直接将左括号压栈会简单一点),比较栈顶元素和遍历到的元素,相等则弹栈,最后判断栈力还有没有元素。

整体代码

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

3、力扣225,用队列模拟栈

使用一个队列和两个队列都可以,使用一个队列就是在弹栈的时候将前面的元素重新从队列末尾加入队列然后弹出队头元素;使用两个队列就是在弹栈的时候将前面的元素放入第二个队列中,然后再放回来。

使用一个队列的整体代码

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

    }
    
    void push(int x) {
        que.push(x);
    }
    
    int pop() {
        int size = que.size();
        size--;
        while (size--) {
            que.push(que.front());
            que.pop();
        }
        int res = que.front();
        que.pop();
        return res;
    }
    
    int top() {
        return que.back();
    }
    
    bool empty() {
        return que.empty();
    }
};

4、力扣232,用栈实现队列

需要使用两个栈,一个用于向队列添加元素,一个用于弹出队头元素。主要关注弹出队头元素的操作

整体代码

class MyQueue {
public:
    stack<int> stIn;
    stack<int> stOut;
    MyQueue() {

    }
    
    void push(int x) {
        stIn.push(x);
    }
    
    int pop() {
        if (stOut.empty()) {
            while (!stIn.empty()) {
                stOut.push(stIn.top());
                stIn.pop();
            }
        }
        int res = stOut.top();
        stOut.pop();
        return res;
    }
    
    int peek() {
        int res = this->pop();
        stOut.push(res);
        return res;
    }
    
    bool empty() {
        return stIn.empty() && stOut.empty();
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值