【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 日相关文章推荐
- LeetCode 199. Binary Tree Right Side View 解题报告
- LeetCode 343. Integer Break 解题报告
- [leetcode] 322. Coin Change 解题报告
- [Leetcode] 588. Design In-Memory File System 解题报告
- LeetCode 401. Binary Watch 解题报告
- LeetCode-Contains Duplicate III-解题报告
- 【LeetCode】Power of Two 解题报告
- [Leetcode] 735. Asteroid Collision 解题报告
- [leetcode] 66. Plus One 解题报告
- [leetcode] One Edit Distance 解题报告
- [Leetcode] 138. Copy List with Random Pointer 解题报告
- [leetcode] 396. Rotate Function 解题报告
- Leetcode 123. Best Time to Buy and Sell Stock III 股票买卖3 解题报告
- [Leetcode] 82. Remove Duplicates from Sorted List II 解题报告
- 【LeetCode】647. Palindromic Substrings 解题报告(Python)
- 【LeetCode】Path Sum II 解题报告
- 【LeetCode】677. Map Sum Pairs 解题报告(Python)
- 【LeetCode】451. Sort Characters By Frequency 解题报告(Python)
- LeetCode-Excel Sheet Column Number-解题报告
- [Leetcode] 342. Power of Four 解题报告