LeetCode Q 438 - 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”.
Similar Question: Longest Substring Without Repeating Characters, Minimum Window Substring, Longest Substring with At Most K Distinct Characters
Solution
Method 1: Sliding Window
Time Complexity: O(n), n is the length of String s.
Code:
public List<Integer> findAnagrams(String s, String p) {
List<Integer> res = new ArrayList<>();
int[] count = new int[26];
for (char ch: p.toCharArray()) count[ch - 'a']++;
int l = 0, r = 0, sum = 0;
while (r < s.length()) {
if (count[s.charAt(r) - 'a'] > 0) sum++;
count[s.charAt(r++) - 'a']--;
if (sum == p.length()) res.add(l);
if (r - l == p.length()) {
if (count[s.charAt(l)] >= 0) sum--;
count[s.charAt(l++)]++;
}
}
return res;
}
Method 2: Naive Method
Time Complexity: O(m * n), n is the length of String s, m is the length of String p.
Code:
public List<Integer> findAnagrams(String s, String p) {
List<Integer> res = new ArrayList<>();
for (int i = 0; i <= s.length() - p.length(); i++) {
String str = s.substring(i, i + p.length());
if (isAnagram(str, p)) res.add(i);
}
return res;
}
private boolean isAnagram(String s, String p) {
int[] count = new int[26];
for (char ch: p.toCharArray()) count[ch-'a']++;
for (char ch: s.toCharArray()) count[ch-'a']--;
for (int i = 0; i < count.length; i++)
if (count[i] != 0) return false;
return true;
}