所以我正在嘗試解決 Leetcode 解碼方式問題(https://leetcode.com/problems/decode-ways/),我發現他們的解決方案令人困惑。
def recursiveWithMemo(self, index, s) -> int:
# If you reach the end of the string
# Return 1 for success.
if index == len(s):
return 1
# If the string starts with a zero, it can't be decoded
if s[index] == '0':
return 0
if index == len(s)-1:
return 1
answer = self.recursiveWithMemo(index 1, s)
if int(s[index : index 2]) <= 26:
answer = self.recursiveWithMemo(index 2, s)
return answer
def numDecodings(self, s: str) -> int:
return self.recursiveWithMemo(0, s)
我無法理解,為什么使用 index == len(s) 和 index == len(s) - 1 條件?index == len(s) - 1 是否不足以檢查我們是否已到達字串末尾?
uj5u.com熱心網友回復:
index == len(s) - 1足以檢查我們是否已到達字串的末尾,但在此演算法中,它們仍在采取 size 步長2。檢查 id index == len(s)不是因為他們想檢查是否到達字串的末尾,而是他們正在檢查這一點,以免在下一行遇到錯誤:
# If the string starts with a zero, it can't be decoded
if s[index] == '0':
return 0
如果index = len(s)條件if s[index] == 0會給你一個錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/446432.html
上一篇:查找附近重復和偽造的影像
