sliding window problem

建立目标string的char to count map
简历window的char to count map
使用一个count变量来计算window中后多少个char符合要求

class Solution(object):
    def findAnagrams(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: List[int]
        """

        charFreq = {}  # target charFreq Map
        for c in p:
            charFreq[c] = charFreq.get(c, 0) + 1
        windows = {}  # keep track of chars in windows
        res = []
        count = 0
        i, j = 0, 0
        while j < len(s):
            if s[j] in charFreq:
                windows[s[j]] = windows.get(s[j], 0) + 1
                if windows[s[j]] <= charFreq[s[j]]:  # windows need this char
                    count += 1
            j += 1  # increase j, extend window
            if j - i == len(p): # window is full
                if count == len(p):
                    res.append(i)
                if s[i] in charFreq:
                    if windows[s[i]] <= charFreq[s[i]]:  # windows don't need this char
                        count -= 1
                    windows[s[i]] -= 1
                i += 1  # increase i, move window
        return res

e438 Find All Anagrams in a String
e219 Contains Duplicate II

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容