forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaximum-repeating-substring.cpp
91 lines (87 loc) · 2.52 KB
/
maximum-repeating-substring.cpp
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Time: O(n), n is the length of sequence
// Space: O(m), m is the length of word
// optimized kmp solution
class Solution {
public:
int maxRepeating(string sequence, string word) {
if (size(sequence) < size(word)) {
return 0;
}
const vector<int> prefix = getPrefix(word);
int result = 0, count = 0, j = -1, prev = -1;
for (int i = 0; i < size(sequence); ++i) {
while (j > -1 && word[j + 1] != sequence[i]) {
j = prefix[j];
}
if (word[j + 1] == sequence[i]) {
++j;
}
if (j + 1 == size(word)) {
count = (i - prev == size(word)) ? count + 1 : 1;
result = max(result, count);
j = -1, prev = i;
}
}
return result;
}
private:
vector<int> getPrefix(const string& pattern) {
vector<int> prefix(size(pattern), -1);
int j = -1;
for (int i = 1; i < size(pattern); ++i) {
while (j > -1 && pattern[j + 1] != pattern[i]) {
j = prefix[j];
}
if (pattern[j + 1] == pattern[i]) {
++j;
}
prefix[i] = j;
}
return prefix;
}
};
// Time: O(n), n is the length of sequence
// Space: O(n)
// kmp solution
class Solution2 {
public:
int maxRepeating(string sequence, string word) {
if (size(sequence) < size(word)) {
return 0;
}
string new_word;
for (int i = 0; i < size(sequence) / size(word); ++i) {
new_word += word;
}
const vector<int> prefix = getPrefix(new_word);
int result = 0, j = -1;
for (int i = 0; i < size(sequence); ++i) {
while (j > -1 && new_word[j + 1] != sequence[i]) {
j = prefix[j];
}
if (new_word[j + 1] == sequence[i]) {
++j;
}
result = max(result, j + 1);
if (j + 1 == size(new_word)) {
break;
}
}
return result / size(word);
}
private:
vector<int> getPrefix(const string& pattern) {
vector<int> prefix(size(pattern), -1);
int j = -1;
for (int i = 1; i < size(pattern); ++i) {
while (j > -1 && pattern[j + 1] != pattern[i]) {
j = prefix[j];
}
if (pattern[j + 1] == pattern[i]) {
++j;
}
prefix[i] = j;
}
return prefix;
}
};