Leetcode解码方式-检查索引两次
所以我试图解决 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)
我无法理解为什么索引 == len(s) 和索引 == len(s) - 1 条件 被使用? index == len(s) - 1 是否不足以检查我们是否已到达字符串末尾?
So I am trying to solve the Leetcode decode ways problem (https://leetcode.com/problems/decode-ways/) and I find their solution confusing.
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)
I am not able to understand, why the index == len(s) and index == len(s) - 1 conditions
are used? Is index == len(s) - 1 not sufficient to check whether we have reached end of string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

index == len(s) - 1
足以检查我们是否已到达字符串末尾,但在此算法中,它们仍然采用大小为2
的步长。检查 idindex == len(s)
并不是因为他们想检查是否到达字符串末尾,而是他们检查这一点以免在下一行中遇到错误:if
index = len(s)
条件if s[index] == 0
会给你一个错误。index == len(s) - 1
is sufficient to check wether we have reached the end of the string, but still in this algorithm they are taking steps of size2
. Checking idindex == len(s)
is not becuase they want to check if they are reached the end of string or not, but rather they are checking this to not to encounter an error in the next line :if
index = len(s)
conditionif s[index] == 0
would give you an error.