-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution28.cpp
More file actions
55 lines (46 loc) · 873 Bytes
/
solution28.cpp
File metadata and controls
55 lines (46 loc) · 873 Bytes
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
#pragma once
#include "solutions.hpp"
// solution no.28
int Solutions::strStr(string haystack, string needle) {
if (needle == "") return 0;
else if (haystack == "") return -1;
int hlen = haystack.length();
int nlen = needle.length();
if (hlen < nlen) return -1;
int* next = getNext(needle, nlen);
bool match = false;
int result = -1;
int i = 0, j = 0;
while (i < hlen && j < nlen) {
if (haystack[i] == needle[j]) {
i++;
j++;
}
else {
if (j == 0) {
i++;
}
else {
j = next[j-1] + 1;
}
}
}
return (j == nlen) ? (i - j): -1;
}
int* Solutions::getNext(string a, int length) {
int i,j;
int* next = new int[length] {-1};
for (i = 1; i < length; i++) {
j = next[i - 1];
while (a[i] != a[j+1] && j >= 0) {
j = next[j];
}
if(a[i] == a[j+1]) {
next[i] = j + 1;
}
else {
next[i] = j;
}
}
return next;
}