LeetCode-Basic Calculator

LiBlog發表於2016-08-31

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23

Note: Do not use the eval built-in library function.

Solution:

public class Solution {
    int index;

    public int calculate(String s) {
        if (s.isEmpty())
            return 0;
        index = 0;
        return calculateRecur("(" + s + ")");
    }

    public int calculateRecur(String s) {
        if (s.charAt(index) == '(') {
            index++;
        }
        
        skipSpace(s);
        int curValue = (s.charAt(index) == '(') ? calculateRecur(s) : getInt(s);
        while (index < s.length()) {
            char nextOper = getOperator(s);
            if (nextOper == ')' || nextOper == 'n')
                break;

            int nextNum = -1;
            if (s.charAt(index) == '(') {
                nextNum = calculateRecur(s);
            } else {
                nextNum = getInt(s);
            }
            curValue = operate(curValue, nextNum, nextOper);
        }
        skipSpace(s);
        return curValue;
    }

    public int operate(int num1, int num2, char oper) {
        if (oper == '+')
            return num1 + num2;
        if (oper == '-')
            return num1 - num2;
        return -1;
    }

    public int getInt(String s) {
        skipSpace(s);
        int val = 0;
        while (index < s.length() && s.charAt(index) >= '0' && s.charAt(index) <= '9') {
            val = val * 10 + (s.charAt(index++) - '0');
        }
        skipSpace(s);
        return val;
    }

    public char getOperator(String s) {
        skipSpace(s);
        char oper = 'n';
        if (index < s.length()) {
            oper = s.charAt(index++);
        }
        // Clear space for the following possible '('.
        skipSpace(s);
        return oper;
    }

    public void skipSpace(String s) {
        while (index < s.length() && s.charAt(index) == ' ') {
            index++;
        }
    }
}