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.
思路:对prefix和suffix分别求hash,如果不mod会TLE
class Solution(object):
def longestPrefix(self, s):
"""
:type s: str
:rtype: str
"""
n = len(s)
prefix = suffix = 0
mul = 1
mod = 10**9+7
res = 0
for i,j in zip(range(n-1),range(n-1,0,-1)):
di,dj = ord(s[i])-ord('a'),ord(s[j])-ord('a'),
prefix = 26*prefix + di
suffix = suffix + mul*dj
prefix %= mod
suffix %= mod
mul *= 26
mul %= mod
if prefix == suffix:
res=i+1
return s[:res]
s=Solution()
print(s.longestPrefix('level'))
print(s.longestPrefix('ababab'))
print(s.longestPrefix('leetcodeleet'))
print(s.longestPrefix('a'))