-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0028.cpp
More file actions
40 lines (40 loc) · 1.2 KB
/
Copy path0028.cpp
File metadata and controls
40 lines (40 loc) · 1.2 KB
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
class Solution {
private:
vector<int> buildLongestPreffixSuffixArray(string const &needle) {
vector<int> lps(needle.length(), 0);
int preffixIdx = 0, suffixIdx = 1;
while (suffixIdx < needle.length()) {
if (needle[preffixIdx] == needle[suffixIdx]) {
lps[suffixIdx] = preffixIdx + 1;
preffixIdx++;
suffixIdx++;
} else if (preffixIdx != 0) {
preffixIdx = lps[preffixIdx - 1];
} else {
suffixIdx++;
}
}
return lps;
}
public:
int strStr(string haystack, string needle) {
if (needle.length() > haystack.length()) return -1;
if (needle.length() == 0) return 0;
vector<int> lps = buildLongestPreffixSuffixArray(needle);
int i = 0, j = 0;
while (i < haystack.length()) {
if (haystack[i] == needle[j]) {
i++;
j++;
} else if (j != 0) {
j = lps[j-1];
} else {
i++;
}
if (j == needle.length()) {
return i - needle.length();
}
}
return -1;
}
};