-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestHappyPrefix.cpp
More file actions
47 lines (34 loc) · 890 Bytes
/
longestHappyPrefix.cpp
File metadata and controls
47 lines (34 loc) · 890 Bytes
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
#include <iostream>
#include <string>
#include <math.h>
// https://leetcode.com/problems/longest-happy-prefix/
class Solution {
public:
std::string longestPrefix(std::string s) {
long prefixHash = 0;
long suffixHash = 0;
long i = 0;
long j = s.size() - 1;
long maxLength = 0;
long mul = 1;
long mod = 1e9 + 7;
while (i < s.size() - 1) {
prefixHash = ((prefixHash * 29) + s[i]) % mod;
suffixHash = (suffixHash + (s[j] * mul)) % mod;
if (prefixHash == suffixHash) {
maxLength = i + 1;
}
mul = mul * 29 % mod;
i += 1;
j -= 1;
}
return s.substr(0, maxLength);
}
};
int main()
{
Solution SolutionInstance;
std::string s = "lel";
std::string result = SolutionInstance.longestPrefix(s);
std::cout << "result is: " << result << std::endl;
}