代码随想录算法训练营第十一天 | ● 20. 有效的括号● 1047. 删除字符串中的所有相邻重复项● 150. 逆波兰表达式求值

文章介绍了C++编程中的三个技术点:使用栈实现有效括号检查,删除字符串中所有相邻重复项,以及逆波兰表达式的求值算法。

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

● 20. 有效的括号

class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        if(s.size()%2!=0) return false;
        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{
                st.pop();
            }
        }
        if(st.empty()){
            return true;
        }else{return false;}
    }
};

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

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

150. 逆波兰表达式求值

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> result;
        for(string e : tokens){
            if(e=="+"||e=="-"||e=="*"||e=="/"){
                int num1 = result.top();
                result.pop();
                int num2 = result.top();
                result.pop();
                if(e=="+"){
                    result.push(num1+num2);
                }else if(e=="-"){
                    result.push(num2-num1);
                }else if(e=="*"){
                    result.push(num1*num2);
                }else{
                    result.push(num2/num1);
                }
            }else{
                result.push(stoi(e));
            }
        }
        int res = result.top();
        result.pop();
        return res;
    }
};

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值