Solve the Equation

Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient.

If there is no solution for the equation, return "No solution".

If there are infinite solutions for the equation, return "Infinite solutions".

If there is exactly one solution for the equation, we ensure that the value of x is an integer.

Example 1:

Input: "x+5-3+x=6+x-2"
Output: "x=2"


Example 2:

Input: "x=x"
Output: "Infinite solutions"


Example 3:

Input: "2x=x"
Output: "x=0"


Example 4:

Input: "2x+3x-6x=x+2"
Output: "x=-1"


Example 5:

Input: "x=x+2"
Output: "No solution"

Solution:

class Solution {
    public String solveEquation(String equation) {
        String[] arr = equation.split("=");
        String left = arr[0];
        String right = arr[1];
        int[] l = eval(left);
        int[] r = eval(right);
        int coe = l[1] - r[1];
        int c = r[0] - l[0];
        if (coe == 0 && c != 0) return "No solution";
        if (coe == 0) return "Infinite solutions";
        int result = c / coe;
        return "x=" + result;
    }
    
    private int[] eval(String left) {
        int leftConst = 0;
        int leftCoefficient = 0;
        int sign = 1;
        for (int i = 0; i < left.length(); i ++) {
            int iStart = i;
            while (i < left.length() && left.charAt(i) != '+' && left.charAt(i) != '-') {
                i ++;
            }
            String term = left.substring(iStart, i);
            if (term.length() > 0) {
                if (term.charAt(term.length() - 1) == 'x') {
                    int coe = term.length() == 1 ? 1 : Integer.parseInt(term.substring(0, term.length() - 1));
                    leftCoefficient += sign * coe;
                } else {
                    int num = Integer.parseInt(term);
                    leftConst += sign * num;
                }
            }
            if (i < left.length()) {
                sign = left.charAt(i) == '+' ? 1 : -1;  
            }
        }    
        return new int[]{leftConst, leftCoefficient};
    }
}