# LeetCode: 640. 求解方程¶

## 1、题目描述¶

输入: "x+5-3+x=6+x-2"



输入: "x=x"



输入: "2x=x"



输入: "2x+3x-6x=x+2"



输入: "x=x+2"



## 2、解题思路¶

• 左右拆分，并且按照序号使用字典保存
• 按照不同情况进行判断即可
class Solution:
def solveEquation(self, equation: str) -> str:
left, right = equation.split("=")

left_atom = left.replace("+", " +").replace("-", " -").split()
right_atom = right.replace("+", " +").replace("-", " -").split()

left_mapping = {1: 0, "x": 0}
right_mapping = {1: 0, "x": 0}
for st in left_atom:
if st == "x":
left_mapping["x"] += 1
elif st[-1] == "x":
if st[-2].isdigit():
left_mapping["x"] += int(st[:-1])
else:
left_mapping["x"] += int(st[:-1] + "1")
else:
left_mapping[1] += int(st)

for st in right_atom:
if st == "x":
right_mapping["x"] += 1
elif st[-1] == "x":
if st[-2].isdigit():
right_mapping["x"] += int(st[:-1])
else:
right_mapping["x"] += int(st[:-1] + "1")
else:
right_mapping[1] += int(st)

left_mapping["x"] -= right_mapping["x"]
right_mapping["x"] = 0
right_mapping[1] -= left_mapping[1]
left_mapping[1] = 0

if left_mapping["x"] == 0:
if right_mapping[1] != 0:
return "No solution"
else:
return "Infinite solutions"

right_mapping[1] //= left_mapping["x"]

return "x=" + str(right_mapping[1])