题目:原题链接(困难)
标签:数学、字符串
解法 | 时间复杂度 | 空间复杂度 | 执行用时 |
---|---|---|---|
Ans 1 (Python) | O ( 1 ) O(1) O(1) | O ( 1 ) O(1) O(1) | 40ms (44.44%) |
Ans 2 (Python) | O ( 1 ) O(1) O(1) | O ( 1 ) O(1) O(1) | 48ms (16.67%) |
Ans 3 (Python) |
解法一(字符串处理):
class Solution:
def isRationalEqual(self, s: str, t: str) -> bool:
def split(ss):
"""将数字拆分为三部分"""
# 形式1:<IntegerPart>
if "." not in ss:
return ss, "", ""
# 形式2:<IntegerPart><.><NonRepeatingPart>
elif "(" not in ss:
p1, p2 = ss.split(".")
return p1, p2, ""
# 形式3:<IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)>
else:
p1, p2 = ss.split(".")
p2, p3 = p2.split("(")
p3 = p3.replace(")", "")
return p1, p2, p3
def clear(p1, p2, p3):
"""处理0.9(9)和0.0(0)的情况"""
if "9" in p3 and p3 == "9" * len(p3):
if "9" in p2 and p2 == "9" * len(p2):
return str(int(p1) + 1), "0", "0"
elif p2 != "":
return p1, str(int(p2) + 1).zfill(len(p2)), "0"
else:
return str(int(p1) + 1), "0", "0"
if p2 == "" and p3 == "":
return p1, "0", "0"
if p3 == "":
return p1, p2, "0"
return p1, p2, p3
# 将数字拆分为三部分
n1, n2, n3 = split(s)
m1, m2, m3 = split(t)
# 处理0.9(9)和0.0(0)的情况
n1, n2, n3 = clear(n1, n2, n3)
m1, m2, m3 = clear(m1, m2, m3)
# print(n1 + "." + n2 + "(" + n3 + ")")
# print(m1 + "." + m2 + "(" + m3 + ")")
if n1 != m1:
return False
while len(n2) < 4:
n2 += n3[0]
n3 = n3[1:] + n3[0]
while len(m2) < 4:
m2 += m3[0]
m3 = m3[1:] + m3[0]
if n2 != m2:
return False
# print(n1 + "." + n2 + "(" + n3 + ")")
# print(m1 + "." + m2 + "(" + m3 + ")")
if len(n3) == 3:
if n3 == n3[0] * 3:
n3 = n3[0]
if len(m3) == 3:
if m3 == m3[0] * 3:
m3 = m3[0]
if len(n3) != len(m3) and (len(n3) == 3 or len(m3) == 3):
return False
if len(n3) < 4:
n3 *= 4 // len(n3)
if len(m3) < 4:
m3 *= 4 // len(m3)
return n3 == m3
解法二(近似比较):
class Solution:
def isRationalEqual(self, s: str, t: str) -> bool:
def count(ss):
if "(" not in ss:
return float(ss)
p1, p2, p3 = ss[:ss.index(".")], ss[ss.index(".") + 1:ss.index("(")], ss[ss.index("(") + 1:-1]
return float(p1 + "." + p2) + int(p3 * 10) / pow(10, 10 * len(p3) + len(p2))
return abs(count(s) - count(t)) < pow(10, -8)