Python - 将总和保存到变量似乎会改变值 - 这是怎么回事? - Leetcode 424. 最长的重复字符替换

问题描述 投票:0回答:0

我有两个相同代码的相似版本 - 一个通过了 Leetcode 424 的所有测试。最长的重复字符替换(在 Python 中解决),另一个没有。我需要帮助来理解为什么第一个版本通过而第二个版本失败。

这里是通过的版本:

class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        window_start, max_len = 0, 0
        char_count = defaultdict(int)
        for window_end in range(len(s)):
            new_char = s[window_end]
            char_count[new_char] += 1
            
            while len(char_count) > 1 and (window_end - window_start + 1) - max(char_count.values()) > k:
                # shrink the window
                char_count[s[window_start]] -= 1
                if char_count[s[window_start]] == 0:
                    del char_count[s[window_start]]
                window_start += 1
             # calculate the length of the window
            max_len = max(max_len, window_end - window_start + 1)
        return max_len

这是失败的版本:

class Solution:    
    def characterReplacement(self, s: str, k: int) -> int:
        window_start, max_len = 0, 0
        char_count = defaultdict(int)
        for window_end in range(len(s)):
            new_char = s[window_end]
            char_count[new_char] += 1
            
            window_size = window_end - window_start + 1
            while len(char_count) > 1 and (window_size) - max(char_count.values()) > k:
                # shrink the window
                char_count[s[window_start]] -= 1
                if char_count[s[window_start]] == 0:
                    del char_count[s[window_start]]
                window_start += 1
            # calculate the length of the window
            max_len = max(max_len, window_end - window_start + 1)
        return max_len

您会注意到两者之间的唯一区别是,在失败版本中,我将此总和保存到一个变量中:

window_end - window_start + 1
,而在通过版本中,我在线计算总和。到底是怎么回事?将这个总和保存到变量的行为是否以某种方式改变了它的值?我很难过。

以下是我已经尝试解决的一些问题:

  • 我尝试添加括号以确保我没有错误的操作顺序但一直得到相同的结果。

  • 最初,当我的代码无法运行时,我感到非常难过,以至于我逐行从我的解决方案转到 Leetcode 上批准的解决方案之一,更改任何差异。我的逻辑流程与解决方案相同。最终,我意识到我的代码和传递代码之间的唯一区别是我将总和保存到一个名为

    window_size
    的变量中。我查阅了有关在 Python 中添加整数的微妙之处的文档,但搜索结果很少。

python sliding-window
© www.soinside.com 2019 - 2024. All rights reserved.