Skip to content

Commit 2e7ede5

Browse files
add problem 28 and test function
1 parent 2572ddb commit 2e7ede5

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

C/1-50/28-Implement-strStr().c

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
* Implement strStr().
3+
4+
* Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
5+
* Created by supercoderx on 2017/8/11.
6+
*/
7+
#include
8+
9+
int strStr(char *haystack, char *needle) {
10+
int len = 0, subLen = 0, diff = 0, isContain = 1;
11+
char *str = haystack;
12+
while (*str != '\0') {
13+
len++;
14+
str++;
15+
}
16+
str = needle;
17+
while (*str != '\0') {
18+
subLen++;
19+
str++;
20+
}
21+
22+
if (subLen > len)
23+
return -1;
24+
25+
diff = len - subLen;
26+
for (int i = 0; i < diff + 1; i++) {
27+
for (int j = i; j < i + subLen; j++) {
28+
if (haystack[j] != needle[j - i]) {
29+
isContain = 0;
30+
break;
31+
}
32+
}
33+
if (isContain == 1)
34+
return i;
35+
isContain = 1;
36+
}
37+
return -1;
38+
}
39+
40+
void testStrStr() {
41+
char *s1 = "abcdefg";
42+
char *s2 = "bcd";
43+
printf("%d", strStr(s1, s2));
44+
}

0 commit comments

Comments
 (0)