Java 6ms Parse Equation approach w/explanation


  • 0

    All equations can be simplified to ax + b = cx +d, when a==c, if(b ≠ d), then there is no solution, if(b==d), there are infinite solutions. If a ≠ c, then ans = (b-d)/(a-c). The challenge is how to parse the coefficients. Here is one possible approach:

    public class Solution {
        
        public String solveEquation(String equation) {
    
            String[] eq = equation.split("=");
    
            int a = process(eq[0])[0];
            int b = process(eq[0])[1];
            int c = process(eq[1])[0];
            int d = process(eq[1])[1];
    
            if(a==c) return (b==d)?"Infinite solutions":"No solution";
    
            return "x=" + String.valueOf((d-b)/(a-c));
        }
    
        public int[] process(String equation){
            // coefficient[0] is coe before x and coefficient[1] is constant
            int[] coefficient  = new int[2];
            int i = 0;
            boolean positive = true;
            while(i < equation.length()){
                if(equation.charAt(i) == '+' || equation.charAt(i) == '-'){
                    positive = (equation.charAt(i) == '+')?true:false;
                    i++;
                    continue;
                    }
                if(equation.charAt(i) == 'x'){
                    coefficient[0] += (positive)?1:-1;
                    }
                if(Character.isDigit(equation.charAt(i))){
                    int sum = 0;
                    while(i < equation.length() && Character.isDigit(equation.charAt(i))){
                        sum = sum*10 + (equation.charAt(i) -'0');
                        i++;
                        }
                    if(i != equation.length() && equation.charAt(i) == 'x'){
                        coefficient[0] += (positive)?sum:-sum;
                        }
                    else{
                        coefficient[1] += (positive)?sum:-sum;
                        i --;
                        }
    
                    }
                i ++;
                }
            return coefficient;
            }
        }
    

Log in to reply
 

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