4ms C short and clean solution with single pass and O(1) space


  • 1
    Z

    This is the simplified version of Basic Calculator II, see my correspond solution here

    /* single operator computation */
    int compute(int lhs, int rhs, char op) {
      if (op == '+') {
        return lhs + rhs;
      }
      if (op == '-') {
        return lhs - rhs;
      }
      return 0;
    }
    
    int calculate(char* s) {
      static int i = 0;
      char c;
      int val = 0;
      char pop = '+';
      int n = 0;
      while (c = s[i++], c != 0) {
        if (c == ' ') {
          continue;
        } else if (c == '(') {
          n = calculate(s);
        } else if (c == ')') {
          break;
        } else if (c == '+' || c == '-') {
          val = compute(val, n, pop);
          pop = c;
          n = 0;
        } else {
          n = n * 10 + c - '0';
        }
      }
      if (c == 0) {
        /* reset function variable */
        i = 0;
      }
      return compute(val, n, pop);
    }

  • 0
    C
    This post is deleted!

  • 0
    C

    A recursive solution is definitely not O(1) space


  • 0
    W

    I agree with cb130619


Log in to reply
 

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