Concise Java Solution


  • 18
    public String solveEquation(String equation) {
        int[] res = evaluateExpression(equation.split("=")[0]),  
      	  res2 = evaluateExpression(equation.split("=")[1]);
        res[0] -= res2[0];
        res[1] = res2[1] - res[1];
        if (res[0] == 0 && res[1] == 0) return "Infinite solutions";
        if (res[0] == 0) return "No solution";
        return "x=" + res[1]/res[0];
    }  
    
    public int[] evaluateExpression(String exp) {
        String[] tokens = exp.split("(?=[-+])"); 
        int[] res =  new int[2];
        for (String token : tokens) {
            if (token.equals("+x") || token.equals("x")) res[0] += 1;
    	else if (token.equals("-x")) res[0] -= 1;
    	else if (token.contains("x")) res[0] += Integer.parseInt(token.substring(0, token.indexOf("x")));
    	else res[1] += Integer.parseInt(token);
        }
        return res;
    }
    

  • 4
    D

    This regex gave me a really great exercise. A neat and clean solution!

    For others who might have difficulty getting the regex, here's a ref: https://stackoverflow.com/questions/10804732/what-is-the-difference-between-and-in-regex


  • 0
    This post is deleted!

  • 0
    J

    Why the comma in [-,+]?


  • 0
    A

    Python version of the solution -

    class Solution(object):
        def solveEquation(self, equation):
            A, B = self.parseSide(equation.split('=')[0]) # Ax+B
            C, D = self.parseSide(equation.split('=')[1]) # Cx+D
            
            #Ax + B = Cx + D 
            if A == C and B != D: 
                return "No solution"
            elif A == C and B == D: 
                return "Infinite solutions"
            else: 
                return "x=" + str((D - B) / (A - C))
            
        def parseSide(self, side):
            tokens = re.findall('[-+]?[0-9]*x?', side)
            
            A,B = 0, 0 #return in the form Ax+B
            for token in tokens: 
                if token == 'x' or token == '+x': A += 1
                elif token == '-x': A -= 1 
                elif 'x' in token: A += int(token[:-1])
                elif len(token) > 0: B += int(token) #our regex could also match empty strings 
            return A,B
    

  • 0

    Another Approach.

    public class Expr {
        private int xw;            // weight of x-coefficient
        private int cw;            // weight of constants
            
        public Expr (String str) {
            int sign = 1;
            Integer num = null;
            for (int idx = 0; idx < str.length(); idx ++) {
                char ch = str.charAt (idx);
                if (ch >= '0' && ch <= '9') {
                    if (num == null) num = 0;
                    num = 10 * num + (ch - '0');
                } else if (ch == 'x') {
                    xw += sign * (num == null ? 1 : num);
                    num = null;
                } else {
                    if (num != null) cw += sign * num;
                    sign = ch == '+' ? 1 : -1;
                    num = null;
                }
            }
                if (num != null) cw += sign * num;
        }
    }
        
    public String solveEquation(String equation) {
        Expr l = new Expr (equation.split ("=") [0]);
        Expr r = new Expr (equation.split ("=") [1]);
            
        if (l.xw == r.xw && l.cw == r.cw) return "Infinite solutions";
        l.xw -= r.xw; l.cw -= r.cw;
            
        if (l.xw == 0) return "No solution";
        return "x=" + (-(l.cw/l.xw));        
    }
    

  • 5

    Nice Solution! Add some comments to make it easier to understand.
    Example:
    x +5 -2x = 6 -3x;
    leftPart : tokens= { x, +5, -2x}; coefficient for x = 1-2 =-1; constant = 5;
    rightPart: tokens= {6, -3x}; coefficient for x = -3; constant = 6;

    final result = (6-5)/ (-1 - (-3))

    public class Solution {
        public String solveEquation(String equation) {
            String[] parts = equation.split("=");
            int[] leftPart = evaluate(parts[0]);
            int[] rightPart = evaluate(parts[1]);
            if(leftPart[0] == rightPart[0] && leftPart[1] == rightPart[1]) {
                return "Infinite solutions";
            }else if (leftPart[0] == rightPart[0]){
                return "No solution";
            }
            return "x="+ (rightPart[1]-leftPart[1])/(leftPart[0]-rightPart[0]);
        }
        
        private int[] evaluate(String str){
            String[] tokens = str.split("(?=[+-])");  // ()for match group; ?= for match and include in res; [+-] means + or -;
            int[] res = new int[2]; // coefficient for x;  coefficient for constant
            for(String token : tokens) {
                if (token.equals("+x") || token.equals("x")) res[0]++; // x means 1x
                else if (token.equals("-x")) res[0]--;// -x means -1x
                else if (token.contains("x")) {
                    res[0] += Integer.parseInt(token.substring(0, token.length()-1)); 
                }else {
                    res[1] += Integer.parseInt(token);
                }
            }
            return res;
        }
    }
    

Log in to reply
 

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