Skip to content

Instantly share code, notes, and snippets.

@dluciano
Created February 5, 2023 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dluciano/6dd162d1c3cd1ac13e00436fede3bc06 to your computer and use it in GitHub Desktop.
Save dluciano/6dd162d1c3cd1ac13e00436fede3bc06 to your computer and use it in GitHub Desktop.
438. Find All Anagrams in a String
public class Solution {
public IList<int> FindAnagrams(string s, string p) {
var pFreq = new int[26];
var sIndex = 0;
var ans = new List<int>();
foreach(var letter in p)
pFreq[letter - 'a']++;
while(sIndex < s.Length){
if(pFreq[s[sIndex] - 'a'] != 0){
var j = 0;
var wFreq = new int[26];
var found = true;
while(j < p.Length && j + sIndex < s.Length){
var curKey = s[j + sIndex] - 'a';
if(pFreq[curKey] == 0){
found = false;
break;
}
wFreq[curKey]++;
if(wFreq[curKey] > pFreq[curKey]){
found = false;
break;
}
j++;
}
if(found){
var fEq = true;
for(var i = 0; i < 26; i++){
if(pFreq[i] != wFreq[i]){
fEq = false;
break;
}
}
if(fEq)
ans.Add(sIndex);
}
}
sIndex++;
}
return ans;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment