438. Find All Anagrams in a String

Given a string s and a non-empty string p, find all the start indices of p’s anagrams in s.

Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.

The order of output does not matter.

Example 1:

Input:
s: “cbaebabacd” p: “abc”

Output:
[0, 6]

Explanation:
The substring with start index = 0 is “cba”, which is an anagram of “abc”.
The substring with start index = 6 is “bac”, which is an anagram of “abc”.

Example 2:

Input:
s: “abab” p: “ab”

Output:
[0, 1, 2]

Explanation:
The substring with start index = 0 is “ab”, which is an anagram of “ab”.
The substring with start index = 1 is “ba”, which is an anagram of “ab”.
The substring with start index = 2 is “ab”, which is an anagram of “ab”.

解题思路:
滑动窗口法,使用 dict 进行对比发现是否是子串

class Solution(object):
    def findAnagrams(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: List[int]
        """
        ls = len(s)
        lp = len(p)
        res = []
        ds = {}
        dp = {}
        for item in p:
            if dp.has_key(item):
                dp[item] += 1
            else:
                dp[item] = 1
        for i in range(ls):
            if i >= lp:
                if ds[s[i-lp]] == 1:
                    del ds[s[i-lp]]
                else:
                    ds[s[i-lp]] -= 1
            if not ds.has_key(s[i]):
                ds[s[i]] = 1
            else:
                ds[s[i]] += 1
            if ds == dp:
                res.append(i-lp+1)
        return res

请多多指教。

文章标题:438. Find All Anagrams in a String

本文作者:顺强

发布时间:2020-04-30, 23:59:00

原始链接:http://shunqiang.ml/leetcode-438-find-all-anagrams-in-a-string/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏