C++ 25 lines, 20ms, clean and easy to understand solution


  • 0
    T
    class Solution {
     public:
        int helper(string& s, int start, int end, int * return_pos){
          int sum = 0, op = 1; // 1 for +; -1 for -
          for (int i = start+1; i < end; i++)
            if (s[i] == ' ') 
                continue;
            else if (s[i] == '+' || s[i] == '-') 
                op = (s[i] == '+') ? 1:-1;
            else if(s[i] == '(')
                sum += op*helper(s, i, end, &i);
            else if(s[i] == ')'){
                *return_pos = i; return sum;
            }else{
                int j = 0, num = 0;
                while (isdigit(s[i+j])) num = num*10 + (s[i+(j++)]-'0');
                i = i+j-1; sum+=op*num;
            }
        
          return sum;
        }
    
        int calculate(string s) {
            if(s.empty()) return 0;
            s = "("+s+")";
            return helper(s, 0, s.size()-1, nullptr);
        }
    };

  • 0
    C

    Thank you! Your solution really helped me!


Log in to reply
 

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