Lintcode 647. Find All Anagrams in a String (Easy) (Python)

647. 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 40,000.

The order of output does not matter.

Example

Given s = “cbaebabacd” p = “abc”

return [0, 6]

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

Code:

class Solution:
    """
    @param s: a string
    @param p: a string
    @return: a list of index
    """
    def findAnagrams(self, s, p):
        # write your code here
        ls, lp = len(s), len(p)
        ds, dp = {},{}
        res = []
        for i in p:
            dp[i] = dp[i]+1 if i in dp else 1
        for i in s[:lp]:
            ds[i] = ds[i]+1 if i in ds else 1
        a = 0
        while a < (ls-lp):
            if ds == dp:
                res.append(a)
            ds[s[a]] -= 1
            if ds[s[a]] == 0:
                del ds[s[a]]
            ds[s[a+lp]] = ds[s[a+lp]] + 1 if s[a+lp] in ds else 1
            a += 1
        if ds == dp:
            res.append(a)
        return res

猜你喜欢

转载自blog.csdn.net/weixin_41677877/article/details/81177417
今日推荐