LeetCode #438: Find All Anagrams in a String

来源:互联网 发布:收银机软件免费 编辑:程序博客网 时间:2024/05/29 18:48

Problem Statement

(Source) 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".

Solution

A “Sliding Window” like algorithm.

class Solution(object):    def findAnagrams(self, s, p):        """        :type s: str        :type p: str        :rtype: List[int]        """        from collections import Counter        res = []        n1, n2 = len(s), len(p)        cnt1, cnt2 = Counter(s[:n2]), Counter(p)        for index in xrange(n1 - n2 + 1):            if cnt1 == cnt2:                res.append(index)            if index == n1 - n2:                break            cnt1[s[index]] -= 1            cnt1[s[index + n2]] += 1            if cnt1[s[index]] == 0:                cnt1.pop(s[index])        return res

[To be optimised]

0 0
原创粉丝点击