【代码随想录】day11|栈与队列part2

本文介绍了三个编程问题的解决方案,分别涉及有效括号的验证、字符串中删除相邻重复字符以及逆波兰表达式的求值,都运用了栈数据结构进行操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

20. 有效的括号

class Solution {
public:
    bool isValid(string s) {
        if(s.size()<2) return false;
        stack<char>stk;
        for(char c:s){
            if(c=='(')   stk.push(')');     //左
            else if(c=='[') stk.push(']');  //左
            else if(c=='{') stk.push('}');  //左
            else if(!stk.empty()&&c==stk.top()){//右,且匹配
                stk.pop();
            }
            else return false;                        
        }
        return stk.empty();
    }
};

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

class Solution {
public:
    string removeDuplicates(string s) {
        stack<char>stk;
        for(char c:s){
            if(!stk.empty()&& c==stk.top()){
                stk.pop();
            }else{
                stk.push(c);
            }
        }
        string ans="";
        while(!stk.empty()){
            ans+=stk.top();
            stk.pop();
        }
        reverse(ans.begin(),ans.end());
        return ans;

    }
};

直接用一个字符串当栈

class Solution {
public:
    string removeDuplicates(string s) {
        string ans="";
        for(char c:s){
            if(!ans.empty()&&ans.back()==c){
                ans.pop_back();
            }else{
                ans.push_back(c);
            }
        }
        return ans;

    }
};

150. 逆波兰表达式求值

注意入栈顺序(计算顺序)和出栈顺序是反过来的

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        long long num1, num2;
        stack<long long> stk;
        for (string s : tokens) {
            if (s == "+" || s == "-" || s == "*"||s == "/") {
                num1 = stk.top();
                stk.pop();
                num2 = stk.top();
                stk.pop();
                if (s == "+")
                    stk.push(num2 + num1);
                else if (s == "-")
                    stk.push(num2 - num1);
                else if (s == "*")
                    stk.push(num2 * num1);
                else if (s == "/")
                    stk.push(num2 / num1);
            }
            else stk.push(stoll(s));            
        }
        return stk.top();
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值