Skip to content

Commit a7ac960

Browse files
author
lightmen
committed
add find-all-anagrams-in-a-string.c
1 parent e49660e commit a7ac960

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Return an array of size *returnSize.
3+
* Note: The returned array must be malloced, assume caller calls free().
4+
*/
5+
int* findAnagrams(char* s, char* p, int* returnSize) {
6+
int *ret;
7+
int hp[256] = {0};
8+
int i;
9+
int ls, lp;
10+
int count, index = 0;
11+
12+
ls = strlen(s);
13+
lp = strlen(p);
14+
count = lp;
15+
ret = malloc(sizeof(int) * ls);
16+
17+
for(i = 0; i < lp; ++i)
18+
hp[p[i]]++;
19+
20+
for(i = 0; i < ls; ++i){
21+
if(hp[s[i]] > 0)
22+
count--;
23+
hp[s[i]]--;
24+
if(i >= lp){
25+
if(hp[s[i - lp]] >= 0)
26+
count++;
27+
hp[s[i - lp]]++;
28+
}
29+
30+
if(count == 0)
31+
ret[index++] = i - lp + 1;
32+
}
33+
34+
*returnSize = index;
35+
return ret;
36+
}

0 commit comments

Comments
 (0)