O(t.length() * s.length())
public class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> list = new ArrayList<>();
// create an array to save the counts for each letter
int[] cnt = new int[26];
int[] tmp;
// count the letter frequency in string p
for (int i=0; i<p.length(); i++)
cnt[p.charAt(i) - 'a']++;
// starting from index 0 check if it is a start index
for (int j=0; j<s.length(); j++) {
tmp = cnt.clone();
int len = 0;
while (j+len < s.length() && len < p.length()) {
if (tmp[s.charAt(j+len) - 'a'] != 0) {
tmp[s.charAt(j+len) - 'a']--;
len++;
}
else break;
}
// found a valid index
if (len == p.length()) list.add(j);
}
return list;
}
}
O(n), sliding window.
public class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> list = new ArrayList<>();
// create a hash table <letter, count>, key is the index(letter), value is count
int[] hash = new int[128];
// count the number of times each letter appeared in p
for (int i=0; i<p.length(); i++)
hash[p.charAt(i)]++;
int left = 0, right = 0, count = p.length();
// increase and decrease the window at the same time (*)
while (right < s.length()) {
// found a letter in p
if (hash[s.charAt(right)] > 0)
count--;
hash[s.charAt(right)]--;
right++;
//when the count is down to 0, means we found the right anagram
//then add window's left to result list
if (count == 0) {
list.add(left);
}
//if we find the window's size equals to p, then we have to move left (narrow the window) to find the new match window
//++ to reset the hash because we kicked out the left
//only increase the count if the character is in p
//the count >= 0 indicate it was original in the hash, cuz it won't go below 0
if (right - left == p.length() ) {
if (hash[s.charAt(left)] >= 0) {
count++;
}
hash[s.charAt(left)]++;
left++;
}
}
return list;
}
}