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

今日任务

232. 用栈实现队列

  • 题目链接: https://leetcode.cn/problems/implement-queue-using-stacks/description/
  • 题目描述

使用栈实现队列的下列操作:

push(x) – 将一个元素放入队列的尾部。 pop() – 从队列首部移除元素。 peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。

示例:

MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek();  // 返回 1
queue.pop();   // 返回 1
queue.empty(); // 返回 false

说明:

你只能使用标准的栈操作 – 也就是只有 push to top, peek/pop from top, size, 和 is empty
操作是合法的。 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。

Solution

class MyQueue {
public:
    MyQueue() {

    }
    
    void push(int x) {
        stackIn.emplace(x);
    }
    
    int pop() {
        int top = peek();
        stackOut.pop();
        return top;
    }
    
    int peek() {
        if(stackOut.empty()){
            while(!stackIn.empty()){
                stackOut.emplace(stackIn.top());
                stackIn.pop();
            }
        }
        return stackOut.top();
    }
    
    bool empty() {
        if(stackIn.empty() && stackOut.empty()){
            return true;
        }
        return false;
    }
private:
    stack<int> stackIn;
    stack<int> stackOut;
};

225. 用队列实现栈

  • 题目链接: https://leetcode.cn/problems/implement-stack-using-queues/description/
  • 题目描述

使用队列实现栈的下列操作:

push(x) – 元素 x 入栈 pop() – 移除栈顶元素 top() – 获取栈顶元素 empty() – 返回栈是否为空

注意:

你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty
这些操作是合法的。 你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 ,
只要是标准的队列操作即可。 你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)

Solution

class MyStack {
public:
    queue<int> que;

    MyStack() {

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

20. 有效的括号

  • 题目链接: https://leetcode.cn/problems/valid-parentheses/description/
  • 题目描述

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

有效字符串需满足:

左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。
示例 1:

输入: “()” 输出: true
示例 2:

输入: “()[]{}” 输出: true
示例 3:

输入: “(]” 输出: false
示例 4:

输入: “([)]” 输出: false
示例 5:

输入: “{[]}”
输出: true

Solution 多种方法

class Solution {
public:
    bool isValid(string s) {
        // stack<char> buffer;
        // for(int i=0;i<s.size();i++){
        //     if(buffer.empty()){
        //         buffer.push(s[i]);
        //         continue;
        //     }
        //     if(s[i]=='}' && buffer.top() == '{'){
        //         buffer.pop();
        //         continue;                
        //     }else if(s[i]==']' && buffer.top() == '['){
        //         buffer.pop();
        //         continue;    
        //     }else if(s[i]==')' && buffer.top() == '('){
        //         buffer.pop();
        //         continue;    
        //     }
        //     buffer.push(s[i]);
        // }

        // return buffer.empty();

        // unordered_map<char,int> m{{'(',1},{'[',2},{'{',3},
        //                           {')',-1},{']',-2},{'}',-3}};
        // stack<char> st;
        // bool istrue=true;
        // for(char c:s){
        //     int flag=m[c];
        //     if(flag>0){
        //         st.push(c);
        //     }else if(!st.empty() && m[st.top()] == -flag){
        //         st.pop();
        //     }else {
        //         istrue=false;
        //         break;
        //     }
        // }
        // if(!st.empty()){
        //     istrue=false;
        // }
        // return istrue;

        if(s.size() % 2){
            return false;
        }
        stack<char> st;
        // unordered_map<char, char> mp = {{')', '('}, {']', '['}, {'}', '{'}};
        // for(char c : s){
        //     if(!mp.contains(c)){
        //         st.emplace(c);
        //     }else{
        //         if(st.empty() || st.top() != mp[c]){
        //             return false;
        //         }
        //         st.pop();
        //     }
        // }
        // return st.empty();

        // unordered_map<char, char> mp = {{'(', ')'}, {'[', ']'}, {'{', '}'}};
        // for(char c : s){
        //     if(mp.contains(c)){
        //         st.emplace(mp[c]);
        //     }else{
        //         if(st.empty() || c != st.top()){
        //             return false;
        //         }
        //         st.pop();
        //     }
        // }
        // return st.empty();

        for(char c : s){
            if(c == '('){
                st.emplace(')');
            }else if(c == '['){
                st.emplace(']');
            }else if(c == '{'){
                st.emplace('}');
            }else{
                if(st.empty() || c != st.top()){
                    return false;
                }
                st.pop();
            }
        }
        return st.empty();
    }
};

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

  • 题目链接: https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/
  • 题目描述

给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。

在 S 上反复执行重复项删除操作,直到无法继续删除。

在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。

示例:

输入:“abbaca” 输出:“ca” 解释:例如,在 “abbaca” 中,我们可以删除 “bb”
由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 “aaca”,其中又只有 “aa”
可以执行重复项删除操作,所以最后的字符串为 “ca”。

提示:

1 <= S.length <= 20000 S 仅由小写英文字母组成

Solution 双指针 | stack

class Solution {
public:
    string removeDuplicates(string s) {
        // stack<char> st;
        // for(char c : s){
        //     if(st.empty()){
        //         st.emplace(c);
        //     }
        //     else if(st.top() == c){
        //         st.pop();
        //     }else{
        //         st.emplace(c);
        //     }
        // }
        // string ans;
        // while(!st.empty()){
        //     ans.append(1, st.top());
        //     st.pop();
        // }
        // reverse(ans.begin(), ans.end());
        // return ans;

        // 双指针法
        int n = s.size();
        if(n < 2){
            return s;
        }
        int left = 0, right = 0;
        // while(right < n){
        //     s[left] = s[right];
        //     if(left > 0 && s[left] == s[left - 1]){
        //         left--;
        //     }else{
        //         left++;
        //     }
        //     right++;
        // }

        while(right < n){
            if(left > 0 && s[left - 1] == s[right]){
                left--;
            }else{
                s[left] = s[right];
                left++;
            }
            right++;
        }
        return s.substr(0, left);
    }
};

其他练习

394. 字符串解码

  • 题目链接: https://leetcode.cn/problems/decode-string/description/?envType=study-plan-v2&envId=selected-coding-interview
  • 题目描述
    在这里插入图片描述

Solution 辅助栈 | 递归 多种写法

class Solution {
public:
    string decodeString(string s) {
        // stack<char> st;
        // for(char c : s){
        //     if(c == ']'){
        //         string tmp = "";
        //         while(st.top() != '['){
        //             tmp.append(1, st.top());
        //             st.pop();
        //         }   
        //         st.pop();
        //         int n = 0;
        //         int len = 0;
        //         while(!st.empty() && isdigit(st.top())){
        //             n += (st.top() - '0') * pow(10, len);
        //             len++;
        //             st.pop();
        //         }
    
        //         while(n--){
        //             for(int i = tmp.size() - 1; i >= 0; i--){
        //                 st.emplace(tmp[i]);
        //             }
        //         }
        //     }else{
        //         st.emplace(c);
        //     }
        // }
        // string ans = "";
        // while(!st.empty()){
        //     ans.append(1, st.top());
        //     st.pop();           
        // }
        // reverse(ans.begin(), ans.end());
        // return ans;

        // 节省空间 辅助栈
        // string ans;
        // stack<pair<int, int>> st;
        // int count = 0;
        // for(char c : s){
        //     if(isalpha(c)){
        //         ans.append(1, c);
        //     }else if(isdigit(c)){
        //         count = count * 10 + c - '0';
        //     }else if(c == '['){
        //         st.emplace(make_pair(count, ans.size()));
        //         count = 0;
        //     }else if(c == ']'){
        //         int n = st.top().first;
        //         int sz = st.top().second;
        //         string tmp = ans.substr(sz);
        //         while(--n){
        //             ans.append(tmp);
        //         }
        //         st.pop();
        //     }
        // }
        // return ans;

        // 递归调用
        // int n = s.size();
        // function<pair<int, string>(int)> dfs = [&](int i) -> pair<int, string>{
        //     int multi = 0;
        //     string ans;
        //     while(i < n){
        //         char c = s[i];
        //         if(isdigit(c)){
        //             multi = multi * 10 + c - '0';
        //         }else if(isalpha(c)){
        //             ans.append(1, c);
        //         }else if(c == '['){
        //             pair<int, string> tmp = dfs(i + 1);
        //             i = tmp.first;
        //             for(int j = 0; j < multi; j++){
        //                 ans.append(tmp.second);
        //             }
        //             multi = 0;
        //         }else{
        //             return {i, ans};
        //         }
        //         i++;
        //     }
        //     return {n, ans};
        // };
        // return dfs(0).second;

        // 递归优化
        int i = 0, n = s.size();
        function<string()> dfs = [&] () -> string{
            string ans;
            int multi = 0;
            while(i < n){
                int c = s[i];
                if(isdigit(c)){
                    multi = multi * 10 + c - '0';
                }else if(isalpha(c)){
                    ans.append(1, c);
                }else if(c == '['){
                    i++;
                    string tmp = dfs();
                    while(multi){
                        multi--;
                        ans.append(tmp);
                    }
                }else{
                    return ans;
                }
                i++;
            }
            return ans;
        };
        return dfs();
    }
};
  • 25
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值