forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain3.cpp
More file actions
69 lines (51 loc) · 1.63 KB
/
main3.cpp
File metadata and controls
69 lines (51 loc) · 1.63 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
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
/// Source : https://leetcode.com/problems/implement-strstr/
/// Author : liuyubobobo
/// Time : 2019-03-11
#include <iostream>
#include <vector>
using namespace std;
/// KMP based on lps
/// Time Complexity: O(n + m)
/// Sapce Complexity: O(m)
class Solution {
public:
int strStr(string haystack, string needle) {
if(haystack == "") return needle == "" ? 0 : -1;
if(needle == "") return 0;
int n = haystack.size(), m = needle.size();
vector<int> lps = getLPS(needle, m); // longest proper prefix which is also suffix
int i = 0, j = 0;
while(i < n){
if(haystack[i] == needle[j]) {
i++, j++;
if (j == needle.size())
return i - needle.size();
}
else if(j) j = lps[j - 1] ;
else i ++;
}
return -1;
}
private:
vector<int> getLPS(const string& pattern, int m){
vector<int> lps(m, 0);
// lps[0] = 0;
int len = 0;
int i = 1;
while(i < m)
if(pattern[i] == pattern[len])
lps[i ++] = ++ len;
// trick part
// a great explanation:
// https://leetcode.com/problems/implement-strstr/discuss/13160/detailed-explanation-on-building-up-lps-for-kmp-algorithm
else if(len) len = lps[len - 1]; // len --
else i ++;
return lps;
}
};
int main() {
cout << Solution().strStr("hello", "ll") << endl; // 2
cout << Solution().strStr("aaaaa", "bba") << endl; // -1
cout << Solution().strStr("mississippi", "issip") << endl; // 4
return 0;
}