-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path5367_longest_happy_prefix.py
More file actions
68 lines (54 loc) · 1.67 KB
/
5367_longest_happy_prefix.py
File metadata and controls
68 lines (54 loc) · 1.67 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
68
'''
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
'''
class Solution:
def longestPrefix(self, s):
PRIME=1000000007
prefixHash = 0
suffixHash = 0
max_i = 0
for i in range(len(s) - 1):
prefixHash = (prefixHash * 26 + (ord(s[i]) - ord('A'))) % PRIME
p = pow(26, i, PRIME)
suffixHash = (suffixHash + p * (ord(s[-i-1]) - ord('A'))) % PRIME
if prefixHash == suffixHash:
max_i = i + 1
return s[:max_i]
def longestPrefix2(self, s):
i = 0
j = 1
array = [0 for _ in range(len(s))]
while j < len(s):
if s[i] == s[j]:
array[j] = i + 1
i += 1
j += 1
elif i == 0:
array[j] = i
j += 1
else:
i = array[i-1]
return s[:array[-1]]
s = Solution()
string = "ababab"
# string = "acccbaaacccbaac"
print(s.longestPrefix2(string))