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

20. 有效的括号

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

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

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

150. 逆波兰表达式求值

class Solution {
    
    
public:
    int evalRPN(vector<string>& tokens) {
    
    
        stack<long long>sta;
        for(int i=0;i<tokens.size();i++){
    
    
            if(tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="*"||tokens[i]=="/"){
    
    
                long long a=sta.top();
                sta.pop();
                long long b=sta.top();
                sta.pop();
                long long c=0;
                if(tokens[i]=="+"){
    
    
                    c=a+b;
                }else if(tokens[i]=="-"){
    
    
                    c=b-a;
                }else if(tokens[i]=="*"){
    
    
                    c=a*b;
                }else {
    
    
                    c=b/a;
                }
                sta.push(c);

            }else{
    
    
                long long count=stoll(tokens[i]);
                sta.push(count);
        }
        
    }
    return sta.top();
    
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43541510/article/details/132120513