Skip to content

Commit a4cd07d

Browse files
committed
Time: 0 ms (100%), Space: 8 MB (23.93%) - LeetHub
1 parent 640f3ad commit a4cd07d

File tree

1 file changed

+42
-6
lines changed

1 file changed

+42
-6
lines changed
Lines changed: 42 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,47 @@
1+
2+
void computeLPS(int m, string& ptr, vector<int>& lps) {
3+
int len = 0, i = 1;
4+
while (i < m) {
5+
if (ptr[i] == ptr[len]) {
6+
len++;
7+
lps[i] = len;
8+
i++;
9+
} else {
10+
if (len != 0) {
11+
len = lps[len - 1];
12+
} else {
13+
i++;
14+
}
15+
}
16+
}
17+
}
18+
19+
20+
int KMP(string& str, string& ptr) {
21+
int n = str.length(), m = ptr.length();
22+
vector<int> lps(m);
23+
computeLPS(m, ptr, lps);
24+
int i = 0, j = 0;
25+
while (i < n) {
26+
if (str[i] == ptr[j]) {
27+
i++, j++;
28+
} else {
29+
if (j != 0) {
30+
j = lps[j - 1];
31+
} else {
32+
i++;
33+
}
34+
}
35+
if (j == m) {
36+
return (i - j);
37+
}
38+
}
39+
return -1;
40+
}
41+
142
class Solution {
243
public:
344
int strStr(string haystack, string needle) {
4-
auto pos = haystack.find(needle);
5-
if(pos != string::npos) {
6-
return pos;
7-
} else {
8-
return -1;
9-
}
45+
return KMP(haystack, needle);
1046
}
1147
};

0 commit comments

Comments
 (0)