Skip to content

Latest commit

 

History

History
 
 

438. Find All Anagrams in a String

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

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

Related Topics:
Hash Table

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/find-all-anagrams-in-a-string/
// Author: github.com/lzl124631x
// Time: O(M + N)
// Space: O(1)
class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        int target[26] = {}, cnt[26] = {};
        for (char c : p) target[c - 'a']++;
        vector<int> ans;
        for (int i = 0; i < s.size(); ++i) {
            if (i >= p.size()) cnt[s[i - p.size()] - 'a']--;
            cnt[s[i] - 'a']++;
            int j = 0;
            for (; j < 26; ++j) {
                if (cnt[j] != target[j]) break;
            }
            if (j == 26) ans.push_back(i - p.size() + 1);
        }
        return ans;
    }
};

Solution 2.

// OJ: https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/536/week-3-may-15th-may-21st/3332/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        int cnt[26] = {};
        vector<int> ans;
        int M = s.size(), N = p.size(), count = N;
        for (char c : p) ++cnt[c - 'a'];
        for (int i = 0; i < M; ++i) {
            if (i >= N && cnt[s[i - N] - 'a']++ >= 0) ++count;
            if (cnt[s[i] - 'a']-- > 0) --count;
            if (!count) ans.push_back(i - N + 1);
        }
        return ans;
    }
};