5ms Java Solution


  • 0
    T
        public String solveEquation(String equation) {
            
            int[] left = parse(equation.substring(0, equation.indexOf("=")));
            int[] right = parse(equation.substring(equation.indexOf("=")+1));
            int aD = left[0] - right[0];
            int bD = right[1] -left[1];
            if(aD == 0 && bD ==0){
                return "Infinite solutions";
            }
            if(aD == 0 && bD != 0){
                return "No solution";
            }
            return "x="+Integer.toString(bD/aD);
        }
        private int[] parse(String s){
            int a = 0;
            int b = 0;
            boolean pos = true;
            int tmp = 0;
            for(int i =0; i<s.length();){
                if(s.charAt(i) == 'x'){
                    if(tmp ==0) {
                        if(i>0 && s.charAt(i-1) == '0'){
                            i++;
                            continue;
                        }
                        tmp = 1;
                    }
                    a += pos?tmp:-tmp;      
                    tmp = 0;
                    i++;
                    continue;
                }
                if(s.charAt(i) == '-' || s.charAt(i) == '+'){
                    b += pos?tmp:-tmp;
                    tmp = 0;
                    pos= s.charAt(i) == '+';
                    i++;
                    continue;
                }
                if(s.charAt(i) <= '9' || s.charAt(i) >= '0'){
                    tmp = tmp*10 + s.charAt(i)-'0';
                    i++;
                    continue;
                }
                throw new RuntimeException("error");
                
            } 
            
            b+= pos?tmp:-tmp;
            return new int[]{a, b};
        }
    

Log in to reply
 

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