Likou 224. Basic Calculator Simulation Stack

https://leetcode-cn.com/problems/basic-calculator/
Insert picture description here
Idea: What a boring problem... Just pay attention to the details, and you can directly recurse.

class Solution {
    
    
public:

    using pr=pair<int,int>;

    pr dfs(const string &s,int idx)
    {
    
    
        int n=s.size(),sum=0,tmp=0,sign=1;
        while(idx<n)
        {
    
    
            if(s[idx]=='(')
            {
    
    
                pr p=dfs(s,idx+1);
                sum+=sign*p.first;
                idx=p.second;
                tmp=0,sign=1;
            }
            else if(s[idx]==')')
                break;
            else if(s[idx]==' ')
                ;
            else if(s[idx]>='0'&&s[idx]<='9')
                tmp=tmp*10+(s[idx]-'0');
            else
            {
    
    
                sum+=sign*tmp;
                tmp=0;
                sign=s[idx]=='+'?1:-1;
            }
            ++idx;
        }
        sum+=sign*tmp;
        return pr(sum,idx);
    }

    int calculate(string s) {
    
    
        return dfs(s,0).first;
    }
};

Or use a stack. The idea is to store the current symbol: the positive sign is 1, and the negative sign is -1. To be precise, it maintains the symbol before the brackets, so that the final correct symbol can be directly calculated within the brackets (equivalent to putting The parentheses are removed and expanded).

class Solution {
    
    
public:
    int calculate(string s) {
    
    
        stack<int> signs;
        int ans=0,sign=1,n=s.size(),tmp=0,i=0;
        signs.push(1);
        while(i<n)
        {
    
    
            if(s[i]==' ')
                ;
            else if(s[i]=='(')
                signs.push(sign);
            else if(s[i]==')')
                signs.pop();
            else if(s[i]=='+')
                sign=signs.top();
            else if(s[i]=='-')
                sign=-signs.top();
            else
            {
    
    
                tmp=0;
                while(i<n&&s[i]>='0'&&s[i]<='9')
                    tmp=tmp*10+(s[i]-'0'),++i;
                ans+=sign*tmp;
                --i;
            }
            ++i;
        }
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/xiji333/article/details/114610372