forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
28.c
98 lines (74 loc) · 2.01 KB
/
28.c
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* KMP algorithm */
void getNext(char* pattern, int* next) {
if (pattern == NULL || next == NULL) return;
int m = strlen(pattern);
int i, j;
next[0] = 0;
j = 0;
for (i = 1; i < m; i++) {
while (j > 0 && pattern[i] != pattern[j])
j = next[j - 1];
if (pattern[i] == pattern[j]) j++;
next[i] = j;
}
}
int strStr(char* haystack, char* needle) {
if (haystack == NULL || needle == NULL) return 0;
int n = strlen(haystack);
int m = strlen(needle);
if (m == 0) return 0;
int *next = (int *)calloc(m, sizeof(int));
getNext(needle, next);
int ans = -1;
int i, j;
j = 0;
for (i = 0; i < n; i++) {
while (j > 0 && haystack[i] != needle[j])
j = next[j - 1];
if (haystack[i] == needle[j]) j++;
if (j == m) {
ans = i + 1 - j;
break; /* if you want to continue search, comment out break */
j = next[j - 1];
}
}
free(next);
return ans;
}
/* Brute force */
int strStr0(char* haystack, char* needle) {
if (haystack == NULL || needle == NULL) return 0;
int n = strlen(haystack);
int m = strlen(needle);
if (m == 0) return 0;
int ans = -1;
int i, j;
j = 0;
for (i = 0; i < n; i++) {
while (j > 0 && haystack[i] != needle[j]) {
i = i + 1 - j;
j = 0;
}
if (haystack[i] == needle[j]) j++;
if (j == m) {
ans = i + 1 - j;
break; /* if you want to continue search, comment out break */
j = 0;
}
}
return ans;
}
int main() {
char str[] = "abcdacabcdabdeabcdabd";
char pattern[] = "abcdabd";
/* 6 */
printf("%d\n", strStr(str, pattern));
/* 0 */
printf("%d\n", strStr("", ""));
/* 0 */
printf("%d\n", strStr("1", ""));
return 0;
}