Skip to content

Commit 11cb16b

Browse files
authored
Create longest-chunked-palindrome-decomposition.cpp
1 parent d039b43 commit 11cb16b

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
// Rabin-Karp Algorithm
5+
class Solution {
6+
public:
7+
Solution() : pow_(N_ + 1, 1) {
8+
for (int i = 1; i < pow_.size(); ++i) {
9+
pow_[i] = (pow_[i - 1] * D_) % MOD_;
10+
}
11+
}
12+
13+
int longestDecomposition(string text) {
14+
int result = 0;
15+
int l = 0, left = 0, right = 0;
16+
for (int i = 0; i < text.length(); ++i) {
17+
++l;
18+
left = (pow_[1] * left + (text[i] - 'a')) % MOD_;
19+
right = (pow_[l - 1] * (text[text.length() - 1 - i] - 'a') + right) % MOD_;
20+
if (left == right &&
21+
compare(text, l, i - l + 1, text.length() - 1 - i)) {
22+
++result;
23+
l = 0, left = 0, right = 0;
24+
}
25+
}
26+
return result;
27+
}
28+
29+
private:
30+
bool compare(const string& text, size_t l, int s1, int s2) {
31+
for (int i = 0; i < l; ++i) {
32+
if (text[s1 + i] != text[s2 + i]) {
33+
return false;
34+
}
35+
}
36+
return true;
37+
}
38+
39+
vector<uint64_t> pow_;
40+
static const int N_ = 1000;
41+
static const uint64_t MOD_ = 1e9 + 7;
42+
static const uint64_t D_ = 26;
43+
};

0 commit comments

Comments
 (0)