438. Find All Anagrams in a String
sliding window, (Array or HashMap)
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
class Solution {
public List<Integer> findAnagrams(String s, String p) {
//sliding window: HashMap
HashMap<Character, Integer> memo = new HashMap<Character, Integer>();
List<Integer> result = new LinkedList<Integer>();
for(int i=0; i<p.length(); i++){
if(memo.containsKey(p.charAt(i))){
memo.put(p.charAt(i), memo.get(p.charAt(i))+1);
}else{
memo.put(p.charAt(i),1);
}
}
int count = p.length();
for(int i=0; i<s.length();i++){
if(memo.containsKey(s.charAt(i))){
if (memo.get(s.charAt(i)) >= 1){
count--;
}
memo.put(s.charAt(i), memo.get(s.charAt(i))-1);
}
if (i>p.length()-1 && memo.containsKey(s.charAt(i-p.length()))){
if(memo.get(s.charAt(i-p.length()))>=0){
count++;
}
memo.put(s.charAt(i-p.length()), memo.get(s.charAt(i-p.length()))+1);
}
if(count == 0) result.add(i-p.length()+1);
}
return result;
}
}
Last updated
Was this helpful?