Leetcode解码方式-检查索引两次

发布于 01-14 19:10 字数 855 浏览 3 评论 0原文

所以我试图解决 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

残疾2025-01-21 19:10:45

index == len(s) - 1 足以检查我们是否已到达字符串末尾,但在此算法中,它们仍然采用大小为 2 的步长。检查 id index == len(s) 并不是因为他们想检查是否到达字符串末尾,而是他们检查这一点以免在下一行中遇到错误:

# If the string starts with a zero, it can't be decoded
if s[index] == '0':
    return 0

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 size 2. Checking id index == 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 the string starts with a zero, it can't be decoded
if s[index] == '0':
    return 0

if index = len(s) condition if s[index] == 0 would give you an error.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文