Leetcode 972:相等的有理數(超詳細的解法!!!)
阿新 • • 發佈:2019-01-09
給定兩個字串 S
和 T
,每個字串代表一個非負有理數,只有當它們表示相同的數字時才返回 true;否則,返回 false。字串中可以使用括號來表示有理數的重複部分。
通常,有理數最多可以用三個部分來表示:整數部分 <IntegerPart>
、小數非重複部分 <NonRepeatingPart>
和小數重複部分 <(><RepeatingPart><)>
。數字可以用以下三種方法之一來表示:
<IntegerPart>
(例:0,12,123)<IntegerPart><.><NonRepeatingPart>
<IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)>
(例:0.1(6),0.9(9),0.00(1212))
十進位制展開的重複部分通常在一對圓括號內表示。例如:
1 / 6 = 0.16666666… = 0.1(6) = 0.1666(6) = 0.166(66)
0.1(6) 或 0.1666(6) 或 0.166(66) 都是 1 / 6 的正確表示形式。
示例 1:
輸入:S = "0.(52)", T = "0.5(25)" 輸出:true 解釋:因為 "0.(52)" 代表 0.52525252...,而 "0.5(25)" 代表 0.52525252525.....,則這兩個字串表示相同的數字。
示例 2:
輸入:S = "0.1666(6)", T = "0.166(66)"
輸出:true
示例 3:
輸入:S = "0.9(9)", T = "1."
輸出:true
解釋:
"0.9(9)" 代表 0.999999999... 永遠重複,等於 1 。[有關說明,請參閱此連結]
"1." 表示數字 1,其格式正確:(IntegerPart) = "1" 且 (NonRepeatingPart) = "" 。
提示:
- 每個部分僅由數字組成。
- 整數部分
<IntegerPart>
不會以 2 個或更多的零開頭。(對每個部分的數字沒有其他限制)。 1 <= <IntegerPart>.length <= 4
0 <= <NonRepeatingPart>.length <= 4
1 <= <RepeatingPart>.length <= 4
解題思路
這個問題如果使用暴力破解的話,那麼這個問題就非常簡單。我們只需要判斷出括號中的數,然後重複個16
次然後新增到字串中。為什麼是16
次?我是試出來的,O(∩_∩)O哈哈~。實在不行,儘量較大的值即可。然後將字串轉換為float
型別,然後判斷輸入的兩個數的差是不是在誤差允許的範圍內即可。
class Solution:
def isRationalEqual(self, S, T):
"""
:type S: str
:type T: str
:rtype: bool
"""
return abs(self.toNumber(S) - self.toNumber(T)) < 1e-15
def toNumber(self, s):
norep, rep = '', ''
n = 0
for i in range(len(s)):
if s[i] == '(':
n = i
norep = s[:i]
elif s[i] == ')':
rep = s[n+1:i]
res = s
if norep != '':
res = norep
if rep != '':
res += rep*16
return float(res)
一個更簡潔的寫法。
class Solution:
def isRationalEqual(self, S, T):
"""
:type S: str
:type T: str
:rtype: bool
"""
def toNumber(s):
i = s.find('(')
if i >= 0:
s = s[:i] + s[i + 1:-1] * 20
return float(s[:20])
return toNumber(S) == toNumber(T)
賊蠢的問題,呵呵。
reference:
https://leetcode.com/problems/equal-rational-numbers/discuss/214203/JavaC%2B%2BPython-Easy-Cheat
我將該問題的其他語言版本新增到了我的GitHub Leetcode
如有問題,希望大家指出!!!