|
34 | 34 |
|
35 | 35 | */
|
36 | 36 | public class _640 {
|
37 |
| - /** |
38 |
| - * Reference: https://discuss.leetcode.com/topic/95203/concise-java-solution/7 |
39 |
| - */ |
40 |
| - public String solveEquation(String equation) { |
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 |
| - } else if (left[0] == right[0]) { |
47 |
| - return "No solution"; |
| 37 | + public static class Solution1 { |
| 38 | + /** |
| 39 | + * Reference: https://discuss.leetcode.com/topic/95203/concise-java-solution/7 |
| 40 | + */ |
| 41 | + public String solveEquation(String equation) { |
| 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 | + } else if (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 |
| - private int[] evaluate(String part) { |
53 |
| - int[] result = new int[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 (String token : tokens) { |
56 |
| - if (token.equals("+x") || token.equals("x")) { |
57 |
| - result[0]++; |
58 |
| - } else if (token.equals("-x")) { |
59 |
| - result[0]--; |
60 |
| - } else if (token.contains("x")) { |
61 |
| - result[0] += Integer.parseInt(token.substring(0, token.length() - 1)); |
62 |
| - } else { |
63 |
| - result[1] += Integer.parseInt(token); |
| 53 | + private int[] evaluate(String part) { |
| 54 | + int[] result = new int[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 (String token : tokens) { |
| 57 | + if (token.equals("+x") || token.equals("x")) { |
| 58 | + result[0]++; |
| 59 | + } else if (token.equals("-x")) { |
| 60 | + result[0]--; |
| 61 | + } else if (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 | + return result; |
65 | 68 | }
|
66 |
| - return result; |
67 | 69 | }
|
68 | 70 | }
|
0 commit comments