DEV Community

Basic Calculator - LeetCode Problem

問題

コード

class Solution {
 public:
  int calculate(string s) {
    long l1 = 0, o1 = 1;  // level one: +, -
    long l2 = 1, o2 = 1;  // level two: *, /
    bool s2 = false;      // weather l2 is set or not
    const int n = s.size();
    for (int i = 0; i < s.size(); i++) {
      auto c = s[i];
      if (isdigit(c)) {  // parse digits
        int last = i + 1;
        for (; last < n; last++) {
          if (!isdigit(s[last])) {
            break;
          }
        }
        long num = stol(s.substr(i, last - i));
        s2 = true;
        i = last - 1;
        l2 = (o2 == 1 ? l2 * num : l2 / num);
      } else if (isalpha(c)) {
        // TODO: parse variable
      } else if (c == '(') {
        int last = i + 1;
        int count = 1;  // parenthesis count
        for (; last < n; last++) {
          if (s[last] == '(') {
            count++;
          } else if (s[last] == ')') {
            count--;
          }
          if (count == 0) {
            break;
          }
        }
        string subExpr = s.substr(i + 1, last - i + 1 - 2);
        int num = calculate(subExpr);
        i = last;
        s2 = true;
        l2 = (o2 == 1 ? l2 * num : l2 / num);
      } else if (c == '*' || c == '/') {
        o2 = (c == '*' ? 1 : -1);
      } else if (c == '+' || c == '-') {
        if (s2) {
          l1 = l1 + o1 * l2;
        }
        o1 = (c == '+' ? 1 : -1);
        s2 = true;
        l2 = o2 = 1;
      } else {  // space
        continue;
      }
    }
    return l1 + o1 * l2;
  }
};

参考: https://leetcode.com/problems/basic-calculator-iii/discuss/113592/Development-of-a-generic-solution-for-the-series-of-the-calculator-problems

Top comments (0)