求解一个给定的方程,将x以字符串 "x=#value" 的形式返回。该方程仅包含 '+' , '-' 操作,变量 x 和其对应系数。
示例 1:
输入: equation = "x+5-3+x=6+x-2"
输出: "x=2"
if (left[0] == 0) {
return "Infinite solutions";
} else {
return "No solution";
}
} else {
return "x=" + (0 - (left[0] / left[1]));
}
-
- class Solution1 {
- public String solveEquation(String equation) {
-
- int[] left = new int[2];
- boolean isAdd = true;
- boolean isLeft = true;
- char[] chars = equation.toCharArray();
- int length = chars.length;
- for (int i = 0; i < length; ) {
-
- char c = chars[i];
- if (Character.isDigit(c)) {
- int v = 0;
- while (i < length && Character.isDigit(chars[i])) {
- v *= 10;
- v += (chars[i] - '0');
- ++i;
- }
-
-
- if (isLeft) {
- if (i < length && chars[i] == 'x') {
- left[1] += v * (isAdd ? 1 : -1);
- ++i;
- } else {
- left[0] += v * (isAdd ? 1 : -1);
- }
- } else {
- if (i < length && chars[i] == 'x') {
- left[1] -= v * (isAdd ? 1 : -1);
- ++i;
- } else {
- left[0] -= v * (isAdd ? 1 : -1);
- }
- }
- } else if (chars[i] == '+') {
- isAdd = true;
- ++i;
- } else if (chars[i] == '-') {
- isAdd = false;
- ++i;
- } else if (chars[i] == '=') {
- isLeft = false;
- isAdd = true;
- ++i;
- } else if (chars[i] == 'x') {
- if (isLeft) {
- left[1] += (isAdd ? 1 : -1);
- } else {
- left[1] -= (isAdd ? 1 : -1);
- }
- ++i;
- }
- }
-
- if (left[1] == 0) {
- if (left[0] == 0) {
- return "Infinite solutions";
- } else {
- return "No solution";
- }
- } else {
- return "x=" + (0 - (left[0] / left[1]));
- }
- }
-
- public static void main(String[] args) {
- Solution1 solution = new Solution1();
- System.out.println(solution.solveEquation("x+5-3+x=6+x-2"));
- }
- }
接着对这个代码进行一次重构,降低代码复杂度,代码实现如下:
- class Solution {
- public String solveEquation(String equation) {
-
- int[] left = new int[2];
- boolean isAdd = true;
- boolean isLeft = true;
- char[] chars = equation.toCharArray();
- int length = chars.length;
- for (int i = 0; i < length; ) {
-
- if (Character.isDigit(chars[i])) {
- int v = 0;
- do {
- v *= 10;
- v += (chars[i] - '0');
- } while (++i < length && Character.isDigit(chars[i]));
-
- if (i < length && chars[i] == 'x') {
- left[1] += v * getOperator(isAdd ^ isLeft);
- ++i;
- } else {
- left[0] += v * getOperator(isAdd ^ isLeft);
- }
-
- } else if (chars[i] == '+') {
- isAdd = true;
- ++i;
- } else if (chars[i] == '-') {
- isAdd = false;
- ++i;
- } else if (chars[i] == '=') {
- isLeft = false;
- isAdd = true;
- ++i;
- } else if (chars[i] == 'x') {
- left[1] += getOperator(isAdd ^ isLeft);
- ++i;
- }
- }
-
- if (left[1] == 0) {
- if (left[0] == 0) {
- return "Infinite solutions";
- } else {
- return "No solution";
- }
- } else {
- return "x=" + (0 - (left[0] / left[1]));
- }
- }
-
- private int getOperator(boolean isAdd) {
- return isAdd ? 1 : -1;
- }
-
- public static void main(String[] args) {
- Solution solution = new Solution();
- System.out.println(solution.solveEquation("x+5-3+x=6+x-2"));
- }
- }
这道题是一道字符串解析题目,然后按照数学方法解决,上述2种实现方式耗时接近,只是减少了代码量。看了看其他人的解决方法,思路基本一致,耗时这块没有看到其他的优化了。如果有更加好的解法方法欢迎回复。