Skip to content

Latest commit

 

History

History
134 lines (90 loc) · 3.78 KB

File metadata and controls

134 lines (90 loc) · 3.78 KB

English Version

题目描述

有一个只含有 'Q', 'W', 'E', 'R' 四种字符,且长度为 n 的字符串。

假如在该字符串中,这四个字符都恰好出现 n/4 次,那么它就是一个「平衡字符串」。

 

给你一个这样的字符串 s,请通过「替换一个子串」的方式,使原字符串 s 变成一个「平衡字符串」。

你可以用和「待替换子串」长度相同的 任何 其他字符串来完成替换。

请返回待替换子串的最小可能长度。

如果原字符串自身就是一个平衡字符串,则返回 0

 

示例 1:

输入:s = "QWER"
输出:0
解释:s 已经是平衡的了。

示例 2:

输入:s = "QQWE"
输出:1
解释:我们需要把一个 'Q' 替换成 'R',这样得到的 "RQWE" (或 "QRWE") 是平衡的。

示例 3:

输入:s = "QQQW"
输出:2
解释:我们可以把前面的 "QQ" 替换成 "ER"。 

示例 4:

输入:s = "QQQQ"
输出:3
解释:我们可以替换后 3 个 'Q',使 s = "QWER"。

 

提示:

  • 1 <= s.length <= 10^5
  • s.length 是 4 的倍数
  • s 中只含有 'Q', 'W', 'E''R' 四种字符

解法

Python3

class Solution:
    def balancedString(self, s: str) -> int:
        # count the occurence of each char
        count_chars = Counter(s)

        required = len(s) // 4

        # hold the number of excessive occurences
        more_chars = defaultdict(int)
        for char, count_char in count_chars.items():
            more_chars[char] = max(0, count_char - required)

        min_len = len(s)

        # count the number of total replacements
        need_replace = sum(more_chars.values())
        if need_replace == 0:
            return 0

        # Sliding windows
        # First, move the second cursors until satisfy the conditions
        # Second, move the first_cursor so that it still satisfy the requirement

        first_cursor, second_cursor = 0, 0
        while second_cursor < len(s):
            # Move second_cursor
            if more_chars[s[second_cursor]] > 0:
                need_replace -= 1
            more_chars[s[second_cursor]] -= 1
            second_cursor += 1

            # Move first_cursor
            while first_cursor < second_cursor and need_replace == 0:
                min_len = min(min_len, second_cursor - first_cursor)
                if s[first_cursor] in more_chars:
                    more_chars[s[first_cursor]] += 1
                    if more_chars[s[first_cursor]] > 0:
                        need_replace += 1
                first_cursor += 1

        return min_len

Java

...