[leetcode] 438. Find All Anagrams in a String

题目

Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

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".

Constraints:

  • 1 <= s.length, p.length <= 3 * 104
  • s and p consist of lowercase English letters.

思路

滑动窗口,先用字典保存p中各字符的数量,随后遍历s,根据出现/离去的字符增减字典的值,并且当字典中所有值为0时,表示得出字谜的一种解法,保存索引至结果中。

代码

python版本:

class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        cnt = Counter(p)
        res = []
        for i in range(len(s)):
            if s[i] in cnt:
                cnt[s[i]] -= 1
            if i-len(p) >= 0 and s[i-len(p)] in cnt:
                cnt[s[i-len(p)]] += 1
            if all([i == 0 for i in cnt.values()]):
                res.append(i-len(p)+1)
        return res

posted @ 2022-03-17 17:10  frankming  阅读(29)  评论(0编辑  收藏  举报