[LeetCode] 438. Find All Anagrams in a String

题:https://leetcode.com/problems/find-all-anagrams-in-a-string/description/

题目

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

思路

题目分析

题目要求 从 s 字符串中 找出 特殊子段的 起始位置。
特殊子段:该子段字母出现的 次数 与 p 字符串 出现的次数完全相同。

解题思路

  • 1.生成 p 对应的窗口格式

  • 2.对 s 生成一个 滑动窗口,滑动窗口用 dict 表示。每向前滑动一个窗口 ,右边字符 在dict中 value 减一,若value == 0 ,同时删除 key值。

  • 3.对比 p 与 s 的窗口。

code

from collections import defaultdict


class Solution:
    def findAnagrams(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: List[int]
        """
        res = []
        windict = defaultdict(lambda: 0)
        pdict = defaultdict(lambda: 0)

        plen = len(p)
        if plen >len(s):
            return res

        for i in range(plen):
            pdict[p[i]] += 1

        for i in range(plen):
            windict[s[i]] += 1
        if windict.items() == pdict.items():
            res.append(0)

        for i in range(plen, len(s)):
            windict[s[i - plen]] -= 1
            if windict[s[i - plen]] == 0:
                del windict[s[i - plen]]
            windict[s[i]] += 1
            if windict.items() == pdict.items():
                res.append(i - plen + 1)
        return res

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/82179971