JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

Solve a given equation and return the value of ‘x’ in the form of a string “x=#value”. The equation contains only ‘+’, ‘-‘ operation, the variable ‘x’ and its coefficient. You should return “No solution” if there is no solution for the equation, or “Infinite solutions” if there are infinite solutions for the equation.

If there is exactly one solution for the equation, we ensure that the value of ‘x’ is an integer.

Example 1:

Input: equation = "x+5-3+x=6+x-2"
Output: "x=2"

Example 2:

Input: equation = "x=x"
Output: "Infinite solutions"

Example 3:

Input: equation = "2x=x"
Output: "x=0"

Constraints:

  • 3 <= equation.length <= 1000
  • equation has exactly one ‘=’.
  • equation consists of integers with an absolute value in the range [0, 100] without any leading zeros, and the variable ‘x’.

Code

coefficient 系数

592. Fraction Addition and Subtraction

Lookahead and lookbehind, collectively called “lookaround”

Look ahead positive (?=): find expression A where expression B follows:
A(?=B)

"a;b;c;d".split("(?=;)");
[a, ;b, ;c, ;d]
class Solution {
    public String solveEquation(String equation) {
        String[] secs = equation.split("=");
        int[] leftRes = helper(secs[0]);
        int[] rightRes = helper(secs[1]);

        int left = leftRes[0] - rightRes[0];
        int right = rightRes[1] - leftRes[1];

        if (left == 0 && right == 0) return "Infinite solutions";
        if (left == 0) return "No solution";

        return "x=" + right / left;
    }

    public int[] helper(String str) {
        String[] tokens = str.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")) {
                int index = token.indexOf("x");
                res[0] += Integer.parseInt(token.substring(0, index));
            } else {
                res[1] += Integer.parseInt(token);
            }
        }

        return res;
    }
}