forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain2.cpp
More file actions
67 lines (51 loc) · 1.7 KB
/
main2.cpp
File metadata and controls
67 lines (51 loc) · 1.7 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
/// Source : https://leetcode.com/problems/implement-strstr/
/// Author : liuyubobobo
/// Time : 2019-03-12
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
/// Rabin-Karp
/// Time Complexity: O(n * m)
/// Sapce Complexity: O(m)
class Solution {
private:
const int MOD = 1e9 + 7;
const int base = 256;
public:
int strStr(string haystack, string needle) {
if(needle == "") return 0;
if(haystack == "") return -1;
int n = haystack.size(), m = needle.size();
if(n < m) return -1;
int h = 1, txthash = 0, patternhash = 0;
for(int i = 0; i < m - 1; i ++){
h = h * 256ll % MOD;
txthash = (txthash * 256ll + haystack[i]) % MOD;
patternhash = (patternhash * 256ll + needle[i]) % MOD;
}
patternhash = (patternhash * 256ll + needle[m - 1]) % MOD;
for(int i = m - 1; i < n; i ++){
txthash = (txthash * 256ll + haystack[i]) % MOD;
if(txthash == patternhash && same(haystack, i - m + 1, i, needle))
return i - m + 1;
txthash -= haystack[i - m + 1] * (long long)h % MOD;
if(txthash < 0) txthash += MOD;
}
return -1;
}
private:
bool same(const string& s, int start, int end, const string& t){
// assert(end - start + 1 == t.size());
for(int i = start; i <= end; i ++)
if(s[i] != t[i - start])
return false;
return true;
}
};
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;
}