My 6ms Java Solution


  • 0
    F
    public class Solution {
        private static class Factors {
            public int numOfX;
            public int constVal;
            
            public Factors(int numOfX, int constVal) {
                this.numOfX = numOfX;
                this.constVal = constVal;
            }
        }
        
        public String solveEquation(String equation) {
            if(equation==null || equation.length()==0) {
                return equation;
            } else {
                String[] exps = equation.split("=");
                Factors fct1 = simplify("+"+exps[ 0 ]);
                Factors fct2 = simplify("+"+exps[ 1 ]);
                int numOfX = fct1.numOfX-fct2.numOfX;
                int constVal = fct2.constVal-fct1.constVal;
                
                if(numOfX == 0) {
                    if(constVal == 0) {
                        return "Infinite solutions";
                    } else {
                        return "No solution";
                    }
                } else {
                    return new StringBuilder("x=").append(constVal/numOfX).toString();
                }
            }
        }
        
        private Factors simplify(String exp) {
            int idx;
            Factors fct = new Factors(0, 0);
            
            for(idx = 0; idx < exp.length(); ) {
                int end, start = idx+1, sign = exp.charAt(idx)=='+'?1:-1;
                
                // Variable "end" must start from a number, not minus or plus sign.
                // It eventually stops at next addition or subtraction operation sign.
                for(end = (exp.charAt(start)=='+' || exp.charAt(start)=='-'?1:0)+start; 
                    end<exp.length() && exp.charAt(end)!='+' && exp.charAt(end)!='-'; 
                    end++);
                idx = end;
                
                if(exp.charAt(end-1) == 'x') {
                    if(start == end-1) {
                        // "+x" or "-x"
                        fct.numOfX += sign;
                    } else if(start == end-2 && (exp.charAt(start)=='+' || exp.charAt(start)=='-')) {
                        // "+-x" or "++x" or "-+x" or "--x"
                        fct.numOfX += sign*(exp.charAt(start)=='+'?1:-1);
                    } else {
                        // "-<signed int>x (for example: -1x, -+2x, --5x)" or "+<signed int>x (for example: +1x, +-7x, ++2x)"
                        fct.numOfX += sign*Integer.valueOf(exp.substring(start, end-1));
                    }
                } else {
                    fct.constVal += sign*Integer.valueOf(exp.substring(start, end));
                }
            }
            
            return fct;
        }
    }
    

Log in to reply
 

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