|
34 | 34 |
|
35 | 35 | */
|
36 | 36 | publicclass_640 {
|
37 |
| -/** |
38 |
| - * Reference: https://discuss.leetcode.com/topic/95203/concise-java-solution/7 |
39 |
| - */ |
40 |
| -publicStringsolveEquation(Stringequation) { |
41 |
| -String[]parts =equation.split("="); |
42 |
| -int[]left =evaluate(parts[0]); |
43 |
| -int[]right =evaluate(parts[1]); |
44 |
| -if (left[0] ==right[0] &&left[1] ==right[1]) { |
45 |
| -return"Infinite solutions"; |
46 |
| - }elseif (left[0] ==right[0]) { |
47 |
| -return"No solution"; |
| 37 | +publicstaticclassSolution1 { |
| 38 | +/** |
| 39 | + * Reference: https://discuss.leetcode.com/topic/95203/concise-java-solution/7 |
| 40 | + */ |
| 41 | +publicStringsolveEquation(Stringequation) { |
| 42 | +String[]parts =equation.split("="); |
| 43 | +int[]left =evaluate(parts[0]); |
| 44 | +int[]right =evaluate(parts[1]); |
| 45 | +if (left[0] ==right[0] &&left[1] ==right[1]) { |
| 46 | +return"Infinite solutions"; |
| 47 | + }elseif (left[0] ==right[0]) { |
| 48 | +return"No solution"; |
| 49 | + } |
| 50 | +return"x=" + (right[1] -left[1]) / (left[0] -right[0]); |
48 | 51 | }
|
49 |
| -return"x=" + (right[1] -left[1]) / (left[0] -right[0]); |
50 |
| - } |
51 | 52 |
|
52 |
| -privateint[]evaluate(Stringpart) { |
53 |
| -int[]result =newint[2];//result[0] is the coefficient for x, result[1] is the coefficient for constants |
54 |
| -String[]tokens =part.split("(?=[+-])");// ()for match group; ?= for match and include in res; [+-] means + or -; |
55 |
| -for (Stringtoken :tokens) { |
56 |
| -if (token.equals("+x") ||token.equals("x")) { |
57 |
| -result[0]++; |
58 |
| - }elseif (token.equals("-x")) { |
59 |
| -result[0]--; |
60 |
| - }elseif (token.contains("x")) { |
61 |
| -result[0] +=Integer.parseInt(token.substring(0,token.length() -1)); |
62 |
| - }else { |
63 |
| -result[1] +=Integer.parseInt(token); |
| 53 | +privateint[]evaluate(Stringpart) { |
| 54 | +int[]result =newint[2];//result[0] is the coefficient for x, result[1] is the coefficient for constants |
| 55 | +String[]tokens =part.split("(?=[+-])");// ()for match group; ?= for match and include in res; [+-] means + or -; |
| 56 | +for (Stringtoken :tokens) { |
| 57 | +if (token.equals("+x") ||token.equals("x")) { |
| 58 | +result[0]++; |
| 59 | + }elseif (token.equals("-x")) { |
| 60 | +result[0]--; |
| 61 | + }elseif (token.contains("x")) { |
| 62 | +result[0] +=Integer.parseInt(token.substring(0,token.length() -1)); |
| 63 | + }else { |
| 64 | +result[1] +=Integer.parseInt(token); |
| 65 | + } |
64 | 66 | }
|
| 67 | +returnresult; |
65 | 68 | }
|
66 |
| -returnresult; |
67 | 69 | }
|
68 | 70 | }
|