LC 2953. 统计完全子字符串

https://leetcode.cn/problems/count-complete-substrings/description/

这里也是看 题解 才知道的,第二个条件比较好处理,主要是第一个条件。没有想到可以通过枚举所有可能重复字符的个数来求解:确定可能重复字符的个数,那么就变成滑动窗口了。在判断是否满足条件的时候,需要在in/out (0,k)两个地方稍微记录一下,这样就可以快速判断是否满足条件。

class Solution:
    def countCompleteSubstrings(self, word: str, k: int) -> int:
        def f(s):
            res = 0
            for m in range(1, 27):
                if k * m > len(word):
                    break
                cnt = [0] * 26
                cat = m
                for i in range(len(s)):
                    j = i - (k * m)
                    if j >= 0:
                        cnt[s[j]] -= 1
                        now = cnt[s[j]]
                        if (now + 1) in (0, k):
                            cat -= 1
                        if now in (0, k):
                            cat += 1

                    cnt[s[i]] += 1
                    if True:
                        now = cnt[s[i]]
                        if (now - 1) in (0, k):
                            cat -= 1
                        if now in (0, k):
                            cat += 1

                    if (i + 1) >= k * m and cat == m:
                        res += 1
            return res

        ss = [ord(x) - ord('a') for x in word]
        ans = 0
        j = 0
        for i in range(len(ss)):
            if i > 0 and abs(ss[i] - ss[i - 1]) > 2:
                ans += f(ss[j:i])
                j = i
        ans += f(ss[j:])
        return ans