Created
February 5, 2023 09:17
-
-
Save dluciano/6dd162d1c3cd1ac13e00436fede3bc06 to your computer and use it in GitHub Desktop.
438. Find All Anagrams in a String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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