Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
longest-duplicate-substring.py 1.32 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2019-05-12 21:33 +08:00 . Update longest-duplicate-substring.py
# Time: O(nlogn)
# Space: O(n)
# other solution is to apply kasai's algorithm, refer to the link below:
# https://leetcode.com/problems/longest-duplicate-substring/discuss/290852/Suffix-array-clear-solution
import collections
class Solution(object):
def longestDupSubstring(self, S):
"""
:type S: str
:rtype: str
"""
M = 10**9+7
D = 26
def check(S, L):
p = pow(D, L, M)
curr = reduce(lambda x, y: (D*x+ord(y)-ord('a')) % M, S[:L], 0)
lookup = collections.defaultdict(list)
lookup[curr].append(L-1)
for i in xrange(L, len(S)):
curr = ((D*curr) % M + ord(S[i])-ord('a') -
((ord(S[i-L])-ord('a'))*p) % M) % M
if curr in lookup:
for j in lookup[curr]: # check if string is the same when hash is the same
if S[j-L+1:j+1] == S[i-L+1:i+1]:
return i-L+1
lookup[curr].append(i)
return 0
left, right = 1, len(S)-1
while left <= right:
mid = left + (right-left)//2
if not check(S, mid):
right = mid-1
else:
left = mid+1
result = check(S, right)
return S[result:result + right]
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助