首页 > 代码库 > 438. Find All Anagrams in a String
438. Find All Anagrams in a String
Problem statement
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".
Solution
This is an anagram problem. As defined from Google translation: "a word, phrase, or name formed by rearranging the letters of another, such as cinema, formed from iceman."
That means all anagrams have the same letters but different combination, obviously, we can get the same string if we sort two anagrams. This is a key two strings to compare.
Solution one: compare each sub-strings(TLE).
- sort the string p
- Loop from s, find the sub-string with the same size with p, sort the sub-string, compare they are equal or not.
Suppose the size of p is m, the size of s is n.
Time complexity is O(nmlgm).
class Solution {public: vector<int> findAnagrams(string s, string p) { sort(p.begin(), p.end()); int size = p.size(); if(s.size() < p.size()){ return {}; } vector<int> indices; for(int i = 0; i <= s.size() - size; i++){ string str = s.substr(i, size); sort(str.begin(), str.end()); if(str == p){ indices.push_back(i); } } return indices; }};
Solution two: sliding window(AC)
This is a very classical idea to solve the problem. We keep a sliding window with the size of string p, recording the appearances of each letter in this window(since all lower case letters). Compare the vector with target(the vector of p).
Update the appearances each time when we move the sliding window.
Time complexity is O(26n) -- > O(n), since 26 is a constant number. space complexity is O(26 * 2) --> O(1), since it does not expand with the size of string increases.
class Solution {public: vector<int> findAnagrams(string s, string p) { vector<int> pv(26, 0), sv(26, 0), indices; if(s.size() < p.size()){ return {}; } for(int i = 0; i < p.size(); i++){ ++sv[s[i] - ‘a‘]; ++pv[p[i] - ‘a‘]; } if(sv == pv){ indices.push_back(0); } for(int i = p.size(); i < s.size(); i++){ ++sv[s[i] - ‘a‘]; --sv[s[i - p.size()] - ‘a‘]; if(sv == pv){ indices.push_back(i - p.size() + 1); } } return indices; }};
438. Find All Anagrams in a String