Java AC Recursive Solution


  • 0
        public int calculate(String s) {
            char[] schar = s.toCharArray();
            int sum = 0;
            char last_operator = '+';
            int i = 0;
            while (i < schar.length){
                if (schar[i] == ' '){
                    i++;
                    continue;
                }
                if (isdigit(schar[i])) {
                    int j = i+1;
                    while (j < schar.length && isdigit(schar[j])) j++;
                    int num = Integer.parseInt(s.substring(i,j));
                    if (last_operator == '+') sum += num;
                    else sum -= num;
                    i = j;
                } else if (schar[i] == '+' || schar[i] == '-') {
                    last_operator = schar[i];
                    i++;
                } else {
                    int left = 1;
                    int j = i+1;
                    while (j < schar.length) {
                        if (schar[j] == '(') left++;
                        else if (schar[j] == ')') left--;
                        if (left == 0) break;
                        j++;
                    }
                    int num = calculate(s.substring(i+1, j));
                    if (last_operator == '+') {
                        sum += num;
                    } else {
                        sum -= num;
                    }
                    i = j+1;
                }
            }
            return sum;
        }
        
        private boolean isdigit(char c) {
            return c >= '0' && c <= '9';
        }

Log in to reply
 

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