Java solution beats 90% no stack


  • 0
    S

    Thanks for great idea from abner. I modified the code to get rid of the stack.

       public int calculate(String s) {
            if (s == null || s.isEmpty()) return 0;
            int num = 0;
            char sign = '+';
            int preValue = 0;
            int result = 0;
            for(int i = 0; i < s.length(); ++i) {
                if(Character.isDigit(s.charAt(i))) {
                    num = num * 10 + s.charAt(i) - '0';
                }
                if (!Character.isDigit(s.charAt(i)) && s.charAt(i) != ' ' || i == s.length() - 1) {
                    if (sign == '+') {
                        result += preValue;
                        preValue = num;
                    }
                    if (sign == '-') {
                        result += preValue;
                        preValue = -num;
                    }
                    if (sign == '*') {
                        preValue *= num;
                    }
                    if (sign == '/') {
                        preValue /= num;
                    }
                    sign = s.charAt(i);
                    num = 0;
                }
            }
            result += preValue;
            return result;
        }
    

Log in to reply
 

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