4
4
// Rabin-Karp Algorithm
5
5
class Solution {
6
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) {
7
+ int longestDecomposition (string text) {
8
+ static const uint64_t MOD = 1e9 + 7 ;
9
+ static const uint64_t D = 26 ;
14
10
int result = 0 ;
15
- int l = 0 , left = 0 , right = 0 ;
11
+ int left = 0 , right = 0 , l = 0 ;
12
+ uint64_t pow_D = 1ull ;
16
13
for (int i = 0 ; i < text.length (); ++i) {
14
+ left = (D * left + (text[i] - ' a' )) % MOD;
15
+ right = (pow_D * (text[text.length () - 1 - i] - ' a' ) + right) % MOD;
17
16
++l;
18
- left = (pow_[1 ] * left + (text[i] - ' a' )) % MOD_;
19
- right = (pow_[l - 1 ] * (text[text.length () - 1 - i] - ' a' ) + right) % MOD_;
17
+ pow_D = (pow_D * D) % MOD;
20
18
if (left == right &&
21
19
compare (text, l, i - l + 1 , text.length () - 1 - i)) {
22
20
++result;
23
- l = 0 , left = 0 , right = 0 ;
21
+ left = 0 , right = 0 , l = 0 , pow_D = 1 ;
24
22
}
25
23
}
26
24
return result;
@@ -35,9 +33,4 @@ class Solution {
35
33
}
36
34
return true ;
37
35
}
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
36
};
0 commit comments