您的位置:首页 > 其它

【LeetCode】438. Find All Anagrams in a String 解题报告

2018-01-27 23:13 423 查看

【LeetCode】438. Find All Anagrams in a String 解题报告

标签(空格分隔): LeetCode

题目地址: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".


Ways

方法一:

这个题考的是时间复杂度。如果判断两个切片是否是排列组合的话,时间复杂度略高,会超时。

能AC的做法是用了一个滑动窗口,每次进入窗口的字符的个数+1,超出滑动窗口的字符个数-1.

这样就一遍就搞定了,而且不用每个切片都算是不是一个排列组合。

Counter大法好,判断两个字符串是否是排列组合直接统计词频然后==判断即可。

注意如果一个词出现的次数是0,那么需要从Counter中移除,因为Counter({‘a’: 0, ‘b’: 1}) w不等于Counter({‘b’: 1})。

from collections import Counter
class Solution(object):
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
answer = []
m, n = len(s), len(p)
if m < n:
return answer
pCounter = Counter(p)
sCounter = Counter(s[:n-1])
index = 0
for index in xrange(n - 1, m):
sCounter[s[index]] += 1
if sCounter == pCounter:
answer.append(index - n + 1)
sCounter[s[index - n + 1]] -= 1
if sCounter[s[index - n + 1]] == 0:
del sCounter[s[index - n + 1]]
return answer


Date

2018 年 1 月 27 日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: