11ms recursive Solution


  • 2
    A
    public class Solution {
        public int calculate(String s) {
            if (s.length() == 0) {
                return 0;
            }
            
            return calculate(s, 0)[0];
        }
        
        public int[] calculate(String s, int i) {
            int sum = 0;
            boolean sign = true;
            
            while (i <= s.length() - 1 && s.charAt(i) != ')') {
                char c = s.charAt(i);
                switch(c) {
                    case '+':
                        sign = true;
                        i++;
                        break;
                    case '-':
                        sign = false;
                        i++;
                        break;
                    case '(':
                        int[] temp = calculate(s, i + 1);
                        i = temp[1];
                        sum += (sign == true ? temp[0] : (-1) * temp[0]);
                        break;
                    case ' ':
                        i++;
                        break;
                    default:
                        int temp2 = 0;
                        while (i <= s.length() - 1 && s.charAt(i) >= '0' && s.charAt(i) <= '9') {
                            temp2 = temp2 * 10 + (s.charAt(i) - '0');
                            i++;
                        }
                        
                        sum += (sign == true ? temp2 : (-1) * temp2);
                        break;
                }
            }
            
            int[] result = {sum, i + 1};
            return result;
        }
    }

Log in to reply
 

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