Recursive descent version C++


  • 0
    B

    Recursive descent, without stack, easier to unserstand!

    class Solution {
    public:
        int j;
        int cal(string s){
            int len = s.length();
            int op = 1;
            int ans = 0;
            while(j < len){
                int tmp = 0;
                if(s[j] == '(') j++, tmp = cal(s), j++;
                else if(s[j] >= '0' && s[j] <= '9'){
                    while(j < len && s[j] >= '0' && s[j] <= '9'){
                        tmp = tmp * 10 + s[j] - '0';
                        j++;
                    }
                }
                ans += op * tmp;
                if(j == len) return ans;
                if(s[j] == ')') return ans;
                else if(s[j] == '+') op = 1;
                else if(s[j] == '-') op = -1;
                j++;
            }
            return ans;
        }
        int calculate(string s) {
            j = 0;
            return cal(s);
        }
    };
    

Log in to reply
 

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