-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy path0438-find-all-anagrams-in-a-string.c
More file actions
47 lines (41 loc) · 1019 Bytes
/
0438-find-all-anagrams-in-a-string.c
File metadata and controls
47 lines (41 loc) · 1019 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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;
}