Java: O(n) time, O(1) space, only use charAt()


  • 0
    F
    public String solveEquation(String equation) {
        int a = 0, b = 0, f = 1, p = 1, sum = 0;
        for (int i = 0; i < equation.length(); i++) {
            if (equation.charAt(i) == '=') {
                f = -1;
                p = 1;
            }
            else if (equation.charAt(i) == '+') p = 1;
            else if (equation.charAt(i) == '-') p = -1;
            else if (equation.charAt(i) == 'x') {
                if (i == 0 || equation.charAt(i - 1) == '+' || equation.charAt(i - 1) == '-' || equation.charAt(i - 1) == '=') sum = 1;
                a += f * p * sum;
                sum = 0;
            }
            else {
                sum = sum * 10 + equation.charAt(i) - '0';
                if (i + 1 == equation.length() || equation.charAt(i + 1) == '+' || equation.charAt(i + 1) == '-' || equation.charAt(i + 1) == '=') {
                    b += f * p * sum;
                    sum = 0;
                }
            }
        }
        if (a == 0 && b == 0) return "Infinite solutions";
        if (a == 0) return "No solution";
        return "x=" + (- b / a);
    }

Log in to reply
 

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