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"
分析:https://leetcode.com/problems/solve-the-equation/discuss/150021/Clear-Java-Code-with-Detailed-Example
Example
e.g. x+5-3+x=6+x-2
- Firstly, we split the equation by "=":
leftPart
is x+5-3+x;rightPart
is 6+x-2; - Secondly, we sum up coefficient and the rest numbers separately, i.e.
leftVals
is 2x + 2, i.e., [2, 2];rightVals
is x + 4, i.e., [1, 4]; - Thirdly, we solve the simplified equation by moving all elements to the left of "=",
cntX = leftVals[0] - rightVals[0];
, i.e., 2 - 1 = 1,cntNum = leftVals[1] - rightVals[1];
, i.e., 2 - 4 = -2,cntX * x + cntNum = 0
, i.e., 1 * x + (-2) = 0,x = (-cntNum) / cntX
, i.e., x = 2
Please note thatexp.split("");
split exp by 0-length string ("a+b-c" to "a", "+", "b", "-", "c")exp.split("(?=[-+])");
split exp by 0-length string only if they are follow by "-" or "+" ("a+b-c" to "a", "+b", "-c")
1 class Solution { 2 public String solveEquation(String equation) { 3 String[] parts = equation.split("="); 4 String leftPart = parts[0]; 5 String rightPart = parts[1]; 6 int[] leftVals = evaluate(leftPart); 7 int[] rightVals = evaluate(rightPart); 8 int cntX = leftVals[0] - rightVals[0]; 9 int cntNum = leftVals[1] - rightVals[1]; 10 if (cntX == 0) { 11 if (cntNum != 0) { 12 return "No solution"; 13 } 14 return "Infinite solutions"; 15 } 16 int valX = (-cntNum) / cntX; 17 StringBuilder result = new StringBuilder(); 18 result.append("x=").append(valX); 19 return result.toString(); 20 } 21 22 private int[] evaluate(String exp) { 23 int[] result = new int[2]; 24 String[] expElements = exp.split("(?=[-+])"); 25 26 for (String ele : expElements) { 27 if (ele.equals("+x") || ele.equals("x")) { 28 result[0]++; 29 } else if (ele.equals("-x")) { 30 result[0]--; 31 } else if (ele.contains("x")) { 32 result[0] += Integer.valueOf(ele.substring(0, ele.indexOf("x"))); 33 } else { 34 result[1] += Integer.valueOf(ele); 35 } 36 } 37 return result; 38 } 39 }