当前位置:网站首页>【LeetCode】640. 求解方程
【LeetCode】640. 求解方程
2022-08-10 11:04:00 【pass night】
题目
求解一个给定的方程,将x以字符串 "x=#value" 的形式返回。该方程仅包含 '+' , '-' 操作,变量 x 和其对应系数。
如果方程没有解,请返回 "No solution" 。如果方程有无限解,则返回 “Infinite solutions” 。
如果方程中只有一个解,要保证返回值 ‘x’ 是一个整数。
示例 1:
输入: equation = "x+5-3+x=6+x-2"
输出: "x=2"
示例 2:
输入: equation = "x=x"
输出: "Infinite solutions"
示例 3:
输入: equation = "2x=x"
输出: "x=0"
提示:
3 <= equation.length <= 1000equation只有一个'='.equation方程由整数组成,其绝对值在[0, 100]范围内,不含前导零和变量'x'。
思路
- 因为方程只包含
+-两种运算符,所以可以直接从左往右解析 - 若方程开头不是符号,则归一化添加
+,若为-则无需添加 - 将方程归一化为 a x + b = 0 ax+b=0 ax+b=0的形式,然后使用数学法求解
- 为了简化代码“Clean Code”,将右式正负颠倒后复用左式的解析函数
代码
class Solution:
def solveEquation(self, equation: str) -> str:
a, b = 0,0
def resolve(expression: str):
nonlocal a,b
i = 0
while i < len(expression):
operator = expression[i]
i += 1
start = i
while i < len(expression) and expression[i] not in "+-":
i += 1
if expression[i-1] == "x":
if operator == "+":
if i-start == 1:
a += 1
else:
a += int(expression[start:i-1])
else:
if i-start == 1:
a -= 1
else:
a -= int(expression[start:i-1])
else:
if operator == "+":
b += int(expression[start:i])
else:
b -= int(expression[start:i])
left, right = equation.split("=")
if left[0] != "-":
left = "+"+left
if right[0] != "-":
right = "+"+right
right = right.translate(str.maketrans("+-", "-+"))
resolve(left)
resolve(right)
if a == 0 and b == 0:
return "Infinite solutions"
elif a == 0 and b != 0:
return "No solution"
else:
return F"x={
-b//a}"
class Solution2:
def solveEquation(self, equation: str) -> str:
left, right = equation.split("=")
if left[0] != "-":
left = "+"+left
if right[0] != "-":
right = "+"+right
# formate ax+b = 0
a, b, i = 0, 0, 0
while i < len(left):
operator = left[i]
i += 1
start = i
while i < len(left) and left[i] not in "+-":
i += 1
if left[i-1] == "x":
if operator == "+":
if i-start == 1:
a += 1
else:
a += int(left[start:i-1])
else:
if i-start == 1:
a -= 1
else:
a -= int(left[start:i-1])
else:
if operator == "+":
b += int(left[start:i])
else:
b -= int(left[start:i])
i = 0
while i < len(right):
operator = right[i]
i += 1
start = i
while i < len(right) and right[i] not in "+-":
i += 1
if right[i-1] == "x":
if operator == "+":
if i-start == 1:
a -= 1
else:
a -= int(right[start:i-1])
else:
if i-start == 1:
a += 1
else:
a += int(right[start:i-1])
else:
if operator == "+":
b -= int(right[start:i])
else:
b += int(right[start:i])
if a == 0 and b == 0:
return "Infinite solutions"
elif a == 0 and b != 0:
return "No solution"
else:
return F"x={
-b//a}"
复杂度
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( 1 ) O(1) O(1)python 字符串是Immutable的,因此替换需要声明一个新的字符串,为此可以分开写,见Solution2
边栏推荐
猜你喜欢

StoneDB Document Bug Hunting Season 1
![[Brave food, not afraid of the linked list of brushing questions] Merging of ordered linked lists](/img/06/9d49fc99ab684f03740deb2abc38e2.png)
[Brave food, not afraid of the linked list of brushing questions] Merging of ordered linked lists

再有人问你分布式事务,把这篇扔给他

AutoCAD Map 3D功能之一暴力处理悬挂点(延伸)

4 of huawei offer levels, incredibly side is easing the bit in the interview ali?

mysql appears: ERROR 1524 (HY000): Plugin '123' is not loaded

Kyligence 通过 SOC 2 Type II 审计,以可信赖的企业级产品服务全球客户

Go 事,Gopher 要学的数字类型,变量,常量,运算符 ,第2篇

Emulate stm32 directly with proteus - the programmer can be completely discarded

推荐6个自媒体领域,轻松易上手
随机推荐
三个绘图工具类详解Paint(画笔)Canvas(画布)Path(路径)
零基础想自学软件测试,有没有大佬可以分享下接下来的学习书籍和路线?
杭电多校-Loop-(不确定性贪心+线段树)
Chapter 22 Source Code File REST API Reference (4)
VSCode remote connection server error: Could not establish connection to "xxxxxx" possible error reasons and solutions
L2 applications from a product perspective: why is it a playground?
YTU 2894: G--我要去内蒙古大草原
3款不同类型的自媒体免费工具,有效提高创作、运营效率
HCIP ---- VLAN
Mount [shell][mount -o loop]
2022年裁员潮,失业程序员何去何从?
Alibaba最新神作!耗时182天肝出来1015页分布式全栈手册太香了
Licking Exercise - 63 Find all anagrams in a string
Do self-media monthly income tens of thousands?Several self-media tools that bloggers are using
Redis设计与实现
blocking non-blocking poll mechanism asynchronous
关于振弦采集模块及采集仪振弦频率值准确率的问题
软件架构简介
Pycharm终端出现PS问题、conda或activate不是内部命令问题..
不止跑路,拯救误操作rm -rf /*的小伙儿