Straightforward logical solution (C++)


  • 0
    S
    class Solution {
        void compress(string& s){
            int begin=0;
            for (int i=0;i<s.size();++i){
                if(s[i]!=' ') s[begin++]=s[i];
            }
            s.resize(begin);
        }
        
        int parseTerm(string& s, int start, int& end){
            int result=parseNumber(s, start, end);
            while(end!=s.size()&&(s[end]=='*'||s[end]=='/')){
                bool op=s[end]=='*';
                start=end+1;
                int term=parseNumber(s,start, end);
                if(op) result*=term;
                else result/=term;
            }
            return result;
        }
        
        int parseNumber(string& s, int start, int& end){
            int result=0;
            while(isdigit(s[start])){
                result*=10;
                result+=s[start]-'0';
                start++;
            }
            end=start;
            return result;
        }
        
        int parseExpression(string s){
            int end=0, start=0;
            int result=parseTerm(s, start, end);
            while(end!=s.size()){
                bool op=s[end]=='+';
                start=end+1;
                int term=parseTerm(s,start, end);
                if(op) result+=term;
                else result-=term;
            }
            return result;
        }
        
    public:
        int calculate(string s) {
            compress(s);
            return parseExpression(s);
        }
    };

Log in to reply
 

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