438. Find All Anagrams in a String
Array
class Solution {
public List<Integer> findAnagrams(String s, String p) {
//sliding window: array
int[] memo = new int[26];
List<Integer> result = new LinkedList<Integer>();
for(int i=0; i<p.length(); i++){
memo[p.charAt(i)-'a']++;
}
int count = p.length();
for(int i=0; i<s.length();i++){
//first add current char to the window
//check if memo contains curent char
// if current char in adjusted p string, memo >=1, count it down
if(memo[s.charAt(i)-'a']-- >=1) count--;
// then remove the first char in the window (i-p.length()),
// if window contains enough elements. i.e. i>p.length()-1;
// if i>p.length()-1, move the left sliding wondow
if (i>p.length()-1 && memo[s.charAt(i-p.length())-'a']++ >=0) count++;
// finally, add the first element of the window (i-p.length()+1) to result
if(count==0) result.add(i-p.length()+1);
}
return result;
}
}HashMap
Last updated
Was this helpful?