Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2220 from seinlin/438
Browse files Browse the repository at this point in the history
Add 0438-find-all-anagrams-in-a-string.c
  • Loading branch information
MHamiid authored Feb 9, 2023
2 parents 40c68ec + fe042d9 commit de10bd9
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions c/0438-find-all-anagrams-in-a-string.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#define TO_INDEX(c) c - 'a'

bool isEquals(int* a, int* b, int n) {
for (int i = 0; i < n; i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}

/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* findAnagrams(char * s, char * p, int* returnSize) {
int sSize = strlen(s);
int pSize = strlen(p);
int pFreq[26] = {0};
int sFreq[26] = {0};
int i, count;
int* ans;

if (sSize < pSize) {
*returnSize = 0;
return ans;
}

for (i = 0; i < pSize; i++) {
pFreq[TO_INDEX(p[i])]++;
sFreq[TO_INDEX(s[i])]++;
}

count = 0;
ans = (int*)calloc(sSize - pSize + 1, sizeof(int));
for (i = 0; i <= sSize - pSize; i++) {
if (i > 0) {
sFreq[TO_INDEX(s[i - 1])]--;
sFreq[TO_INDEX(s[i + pSize - 1])]++;
}
if (isEquals(sFreq, pFreq, 26)) {
ans[count++] = i;
}
}
*returnSize = count;

return ans;
}

0 comments on commit de10bd9

Please sign in to comment.