我有以下函式計算字串中唯一回文的數量。我試圖通過跟蹤索引來提高演算法效率,以避免在遞回中每次都呼叫切片字串。但是,當向遞回函式cp2添加索引引數時,我得到了對堆疊的最大呼叫。有人可以解釋為什么會這樣嗎?
def countPalindrones(word, d):
count = 0
if word in d:
return d[word]
if len(word) == 0:
return 1
for i in range(len(word)):
if isPalindrone(word[:i 1]):
count = countPalindrones(word[i 1:], d)
d[word] = count
return count
# overflow ???
def cp2(word, index, d):
count = 0
if word[index:] in d:
return d[word[index:]]
if len(word[index:]) == 0:
return 1
for i in range(len(word[index:])):
if isPalindrone(word[index:][:i 1]):
count = cp2(word, i 1, d)
d[word[index:]] = count
return count
uj5u.com熱心網友回復:
當您進行遞回呼叫時,您是從 index 開始1,而不是從index. 遞回應該是:
count = cp2(word, index i 1, d)
此外,您可以從,而不是i 1開始您的范圍,而不是在回圈中撰寫。10
for i in range(1, len(word[index:])):
if isPalindrone(word[index:][:i]):
count = cp2(word, i, d)
d[word[index:]] = count
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/429509.html
下一篇:在javascript中使用filter()來實作curriable()是可行的,但是,uisngmap()是可行的,為什么?
