C++ c-style solution in O(1) space,hope can help


  • 0
    Z
    class Solution {
    public:
        int calculate(string s) {
            unordered_set<char> ops({'+','-','*','/'});
            s='+'+s+'+';
            int res=0,i=0;         
            char pre='+';
            while(i<s.size()-1){
                int t=i+1;
                while(!ops.count(s[++i]));
                int tmp=atoi(s.substr(t,i-t).c_str());          
                if(s[i]=='*'||s[i]=='/'){
                    while(s[i]=='*'||s[i]=='/'){
                    int t=i+1;
                    while(!ops.count(s[++i]));
                    int post=atoi(s.substr(t,i-t).c_str());
                    if(s[t-1]=='*')tmp*=post;
                    else tmp/=post;
                    }
                }
                if(pre=='+')res+=tmp;
                else res-=tmp;
                pre=s[i];
            }
            return res;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.