1. 程式人生 > >leetcode之Find All Anagrams in a String(438)

leetcode之Find All Anagrams in a String(438)

題目:

給定一個字串 和一個非空字串 p,找到 中所有是 的字母異位詞的子串,返回這些子串的起始索引。

字串只包含小寫英文字母,並且字串 和 的長度都不超過 20100。

說明:

  • 字母異位詞指字母相同,但排列不同的字串。
  • 不考慮答案輸出的順序。

示例 1:

輸入:
s: "cbaebabacd" p: "abc"

輸出:
[0, 6]

解釋:
起始索引等於 0 的子串是 "cba", 它是 "abc" 的字母異位詞。
起始索引等於 6 的子串是 "bac", 它是 "abc" 的字母異位詞。

 示例 2:

輸入:
s: "abab" p: "ab"

輸出:
[0, 1, 2]

解釋:
起始索引等於 0 的子串是 "ab", 它是 "ab" 的字母異位詞。
起始索引等於 1 的子串是 "ba", 它是 "ab" 的字母異位詞。
起始索引等於 2 的子串是 "ab", 它是 "ab" 的字母異位詞。

python程式碼1(未AC):

class Solution(object):
    def findAnagrams(self, s, p):
        res = []
        for i in range(len(s)-len(p)+1):
            if self.creatDict(s[i:i+len(p)]) == self.creatDict(p):
                res.append(i)
        return res
    def creatDict(self,s):
        res = {}
        for i in s:
            if i in res:
                res[i] += 1
            else:
                res[i] = 1
        return res

python程式碼2:

class Solution(object):
    def findAnagrams(self, s, p):
        from collections import Counter
        res = []
        pCounter = Counter(p)
        sCounter = Counter(s[:len(p)-1])
        for i in range(len(p)-1,len(s)):
            sCounter[s[i]] += 1
            if sCounter == pCounter:
                res.append(i-len(p)+1)
            sCounter[s[i-len(p)+1]] -= 1
            if sCounter[s[i-len(p)+1]] == 0:
                del sCounter[s[i-len(p)+1]]
        return res