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:

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

Link:

https://leetcode.com/problems/find-all-anagrams-in-a-string/#/description

解题方法:

用字符的分布来匹配anagrams,用slide window来优化暴力算法。当i>p的长度时,每次i++都相当于窗口右移动。左边需要减去刚刚划过的记录。

Tips:

不能用unordered_map来当哈希表。

Time Complexity:

O(n)

完整代码:

vector<int> findAnagrams(string s, string p) 
    {
        vector<int> result;
        int lenp = p.size();
        int lens = s.size();
        if(s.size() == 0 || p.size() > s.size())
            return result;
        vector<int> hash1(26);
        vector<int> hash2(26);
        for(auto a: p)
            hash1[a-'a']++;
        for(int i = 0; i < s.size(); i++)
        {
            hash2[s[i]-'a']++;
            if(i >= lenp) hash2[s[i-lenp]-'a']--;  //加上右边的记录,减去左边的记录
            if(hash1 == hash2) result.push_back(i-lenp+1);  
        }
        return result;   
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,426评论 0 23
  • 如何成为一个很厉害的人? 1.即刻行动 不要把小事堆积成心理成本。拖地、洗碗、买菜、做饭、缴费,能够处理的,即刻行...
    一溪风月阅读 1,787评论 2 5
  • 婚姻中要维持爱,唯一的途径是不断地分分合合。 因为只有情人才分分合合,而维系情人的恰恰是爱。爱是一切的答案,其他都...
    大眼猫阅读 2,860评论 0 0