1044. Longest Duplicate Substring

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:

  1. 2 <= S.length <= 10^5
  2. 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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值