-
Notifications
You must be signed in to change notification settings - Fork 160
/
Firstanagram.cpp
77 lines (61 loc) · 1.84 KB
/
Firstanagram.cpp
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
Find the first anagram's first index of a given string in another string.
If it does not exist, return -1.
*/
/*
solution: use a sliding window to save and count the change of char symbol frequency
O(n) time, O(1) space, where n is the length of string we search.
*/
#include<iostream>
#include<cassert>
using namespace std;
//src points to the target string, str points to the string we search
int FindFirstAnagram(char *str, char *src) {
assert(str && src);
int srcl = strlen(src);
int strl = strlen(str);
if (srcl > strl) return -1;
char *p = src;
int nfind[256];
memset(nfind, 0, sizeof(nfind));
//number of char symbols
int count = 0;
while(*p != 0) {
if (nfind[*p]++ == 0)
count++;
p++;
}
int afind[256];
memset(afind, 0, sizeof(afind));
int match = 0;
char *iter = str;
for (int i = 0; i < srcl; i++) {
if (++afind[*iter] == nfind[*iter])
match++;
iter++;
}
while (*iter != 0 && match != count){
//if it will match at the end of windwow by increase one count
if (afind[*iter] + 1 == nfind[*iter])
match++;
//if it already match at the end of windwow
if (afind[*iter] == nfind[*iter] && nfind[*iter] != 0)
match--;
//it it will match at the begin of window by decrease on count
if (afind[*(iter - srcl)]-1 == nfind[*(iter-srcl)] && nfind[*(iter-srcl)] != 0)
match++;
//if it already match at the begin of window
if (afind[*(iter - srcl)] == nfind[*(iter - srcl)])
match--;
afind[*iter]++;
afind[*(iter - srcl)]--;
iter++;
}
return (match == count) ? (iter-str-srcl) : -1;
}
int main() {
char *l = "brafasfjknvasfasadsaraa";
char *s = "asff";
cout<<FindFirstAnagram(l,s)<<endl;
return 0;
}