Given a string S
, consider all duplicated substrings: (contiguous) substrings of S that occur 2 or more times. (The occurrences may overlap.)
Return any duplicated substring that has the longest possible length. (If S
does not have a duplicated substring, the answer is ""
.)
Example 1:
Input: "banana" Output: "ana"
Example 2:
Input: "abcd" Output: ""
Note:
2 <= S.length <= 10^5
S
consists of lowercase English letters.
思路:二分。为了节省内存,将string hash成整数(用了mod,能AC是因为数据量不是很大)
为了降低hash的时间,利用前面substring的hash结果
class Solution(object):
def longestDupSubstring(self, S):
"""
:type S: str
:rtype: str
"""
mod=2**63-1
def hash(s):
ss=[ord(c)-ord('a') for c in s]
res=0
for c in ss:
res*=26
res+=c
res%=mod
return res
def hash2(prev,pre_char,cur_char,const):
return ((prev-const*(ord(pre_char)-ord('a')))*26+(ord(cur_char)-ord('a')))%mod
def ok(mid):
const=(26**(mid-1))%mod
cur_hash = hash(S[:mid])
s=set()
s.add(cur_hash)
for i in range(1,len(S)-mid+1):
sub_hash = hash2(cur_hash,S[i-1],S[i+mid-1],const)
cur_hash = sub_hash
if sub_hash in s: return True,S[i:i+mid]
s.add(sub_hash)
return False,''
lo,hi=1,len(S)-1
res=''
while lo<hi:
mid=(lo+hi)//2
f,r=ok(mid)
if f:
res=r
lo=mid+1
else:
hi=mid-1
f,r=ok((lo+hi)//2)
if f: res=r
return res
这场比赛打下来,发现自己成智障了,ciao