LeetCode 1044
在确定长度的时候使用RK来进行查找,然后用2叉查找来找到对应的长度。
class Solution:
def __init__(self):
self.M = 1000000000000000003
self.R = 26
self.RK = 1
def longestDupSubstring(self, s: str) -> str:
if s == None or len(s) == 0: return 0
result = ""
def hasKRepeat(s:str, K:int) -> bool:
nonlocal result
if K == 0: return True
self.RK = 1
for i in range(K-1):
self.RK = (self.RK * self.R) % self.M
left = 0
right = left + K
hash1 = 0
hashs = set()
for i in range(0, right):
hash1 = (hash1 * self.R + ord(s[i]) - ord('a'))%self.M
hashs.add(hash1)
while right < len(s):
hash1 = ((hash1 - (ord(s[left]) -ord('a')) * self.RK)*self.R + ord(s[right]) - ord('a'))%self.M
if (hash1 in hashs):
if len(result) < right - left:
result = s[left+1:right+1]
return True
hashs.add(hash1)
right +=1
left +=1
return False
left = 0
right = len(s)-1
while left <= right:
mid = left + ((right-left) >> 1)
if hasKRepeat(s, mid):
left = mid + 1
else:
right = mid -1
return result
第一版的代码没有加上取模的部分,字符串不是很长的情况下都是可以的,在非常长的字符串情况下就开始有内存的问题了,参考了其他人加上取模之后解决掉了。