其他分享
首页 > 其他分享> > LC.424. Longest Repeating Character Replacement

LC.424. Longest Repeating Character Replacement

作者:互联网

在这里插入图片描述

class Solution1(object):
    def characterReplacement(self, s, k):
        """
        这道题的核心是子串中,字串的长度减去出现最高频的次数要小于等于k
        我们用一个长度为26的数组char_count去记录频次
        用滑动窗口去确定当前的字串,当不满足条件时,左边就要收缩串口,同时更新char_count
        """
        char_count = [0] * 26
        left, result = 0, 0
        for right in range(len(s)):
            char_count[ord(s[right]) - ord("A")] += 1
            if right - left + 1 - max(char_count) <= k:
                result = max(result, right- left +1)
            else:
                while(right - left + 1 - max(char_count) > k):
                    char_count[ord(s[left]) - ord("A")] -=1
                    left += 1
        return result




class Solution2(object):
    """
    上述方法的优化,上面的方法中不必每次都去char_count中找最大值,
    """
    def characterReplacement(self, s, k):
        char_count = [0] * 26
        left, top_count, top_frq, result = 0, 0, 0, 0
        for right in range(len(s)):
            char_count[ord(s[right]) -ord("A")] += 1
            if char_count[ord(s[right]) -ord("A")] > top_frq:
                top_count = 1
                top_frq = char_count[ord(s[right]) -ord("A")]
            if char_count[ord(s[right]) -ord("A")]  == top_frq:
                top_count += 1

            if  right - left + 1 - top_frq <= k:
                result = max(result, right - left + 1)
            else:
                while(right - left + 1 - top_frq > k):
                    if  char_count[ord(s[left]) - ord("A")] == top_frq:
                        top_count -= 1
                    char_count[ord(s[left]) - ord("A")] -= 1
                    if top_count == 0:
                        top_frq = max(char_count)
                    top_count = 0
                    for frq in char_count:
                        if frq == top_frq:
                            top_count += 1
                    left += 1
        return result

标签:count,right,top,Character,char,frq,Repeating,ord,Replacement
来源: https://blog.csdn.net/dpengwang/article/details/91359988