438. Find All Anagrams in a String (Medium)

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

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

Solutions

``````class Solution {

// The key idea for this problem is that anagrams are of same length and the frequence of different
// chars are identical.

// We may image a window of the same length as p and work out the character
// frequence in this window.

// We define two arrays of length 256 of which one keeps the char frequence of p and the other keeps s's.

// we update the char frequence in the window when scanning the given string. We hit the anagram string
// as long as the frequence matches.

public List<Integer> findAnagrams(String s, String p) {
List<Integer> ans = new ArrayList<>();

if (s == null || p == null || s.length() < p.length()) {
return ans;
}

// window size
int ws = p.length();

// frequence map for chars in pattern string
int[] freqP = new int[26];
Arrays.fill(freqP, 0);

for (int i = 0; i < p.length(); i++) {
freqP[p.charAt(i) - 'a']++;
}

// frequence map for chars in test string of moving window
int[] freqS = new int[26];
Arrays.fill(freqS, 0);

for (int i = 0; i < s.length(); i++) {
// The new element incorporated when window moving forward
int cRight = s.charAt(i) - 'a';

freqS[cRight]++;

if (i < ws - 1) {
continue;
}

if (i > ws - 1) {
// the leftmost element of previous window. It is edged off when window
// moving forward.
int cLeft = s.charAt(i - ws) - 'a';

freqS[cLeft]--;
}

boolean isAnagram = true;

for (int j = 0; j < 26; j++) {
if (freqS[j] == freqP[j]) {
continue;
}

isAnagram = false;
break;
}

if (isAnagram) {
ans.add(i - ws + 1);
}
}

return ans;
}
}
``````

References

Copyright © iovi.com 2017 all right reserved，powered by GitbookLast Modification: 2019-12-03 11:01:18