File tree Expand file tree Collapse file tree 2 files changed +55
-0
lines changed
0438_find_all_anagrams_in_a_string Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ all :
2+ gcc -O1 -o test anagrams_in_string.c
Original file line number Diff line number Diff line change 1+ #include <stdio.h>
2+ #include <stdlib.h>
3+
4+
5+ /**
6+ * Note: The returned array must be malloced, assume caller calls free().
7+ */
8+ int * findAnagrams (char * s , char * p , int * returnSize ){
9+ * returnSize = 0 ;
10+ int * res = malloc (11000 * sizeof (int ));
11+ int i , pat_len = 0 ;
12+ int count [128 ] = { 0 };
13+ for (i = 0 ; p [i ] != '\0' ; i ++ ) {
14+ count [p [i ]]++ ;
15+ }
16+ pat_len = i ;
17+
18+ int l = 0 , r = 0 , len = 0 ;
19+ while (s [r ] != '\0' ) {
20+ if (-- count [s [r ++ ]] >= 0 ) {
21+ len ++ ;
22+ }
23+ if (r - l >= pat_len ) {
24+ if (len == pat_len ) {
25+ res [(* returnSize )++ ] = l ;
26+ }
27+ if (++ count [s [l ++ ]] > 0 ) {
28+ len -- ;
29+ }
30+ }
31+ }
32+
33+ return res ;
34+ }
35+
36+ int main (int argc , char * * argv )
37+ {
38+ if (argc != 3 ) {
39+ fprintf (stderr , "Usage: ./test string pattern\n" );
40+ exit (-1 );
41+ }
42+
43+ char * t = argv [1 ];
44+ char * s = argv [2 ];
45+ int i , count ;
46+ int * results = findAnagrams (s , t , & count );
47+ for (i = 0 ; i < count ; i ++ ) {
48+ printf ("%d " , results [i ]);
49+ }
50+ printf ("\n" );
51+
52+ return 0 ;
53+ }
You can’t perform that action at this time.
0 commit comments