-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimplement-strstr.cpp
39 lines (37 loc) · 1.04 KB
/
implement-strstr.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
class Solution {
public:
char *strStr(char *haystack, char *needle) {
if (*needle == '\0')
return haystack;
char *pStart = haystack;
int needleSum = 0;
int needleCount = 0;
for(char *p = needle; *p != '\0'; p++) {
needleSum += *p;
needleCount++;
}
int pStartSum = 0;
for(int i = 0; i < needleCount; i++) {
if (pStart[i] == '\0')
return NULL;
pStartSum += pStart[i];
}
while (*pStart) {
if (pStartSum == needleSum && sameString(pStart, needle, needleCount)){
return pStart;
}
pStartSum -= *pStart;
pStart++;
pStartSum += pStart[needleCount-1];
}
return NULL;
}
bool sameString(char *a, char *b, int n) {
int i = 0;
while (i < n && *a && *b && *a == *b) {
a++;
b++;
}
return (*b == '\0');
}
};