Datastructure and Algorithm: DAY 71. Leetcode: 248/2736
Description
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.
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'.
Solution
Move all expressions to the left
Then all minus signs are preceded by a plus sign as a prefix
Divide the equation by plus sign
Count the number of x and the operation result of the number
classSolution: defsolveEquation(self, equation: str) -> str: left, right = equation.split("=") new_left = [] new_right = [] if right[0] != "-": right = "+" + right
for i inrange(len(left)): if left[i] == "-": new_left.append("+-") else: new_left.append(left[i]) for i inrange(len(right)): if right[i] == "+": new_right.append("+-") elif right[i] == "-": new_right.append("+") else: new_right.append(right[i]) e = "".join(new_left)+"".join(new_right)
print(e.split("+")) letter = 0 num = 0 for cur in e.split("+"): sign, coe, l = 1, 0, 0 if cur: if cur[0] == "-": sign = -1 if cur[-1] == "x": coe = int(cur[1:-1]) iflen(cur) > 2else1 letter += sign * coe else: num += int(cur) else: if cur[-1] == "x": coe = int(cur[:-1]) iflen(cur) > 1else1 letter += sign * coe else: num += int(cur) if letter == num == 0: return"Infinite solutions" elif letter == 0and num != 0: return"No solution" else: v = int(-num / letter) return"x="+str(v)