466. Count The Repetitions

class Solution(object):
    
    def getMaxRepetitions(self, s1, n1, s2, n2):
        #http://www.cnblogs.com/grandyang/p/6149294.html
        #memoization: use dictionary to find loop where x*s1 contains y*s2, and each loop start with the same index of s2 
        #key=next_index, val=(s1_rep,s2_rep)
        #each item indicates, for s1_rep reps of s1, there are maximum s2_rep reps of s2 and the next_index of s2 to search for is next_index
        rep_count={} 
        s1_rep,s2_rep,next_index=0,0,0
        
        while s1_rep<n1:
            print rep_count
            s1_rep+=1
            for ch in s1:
                if ch==s2[next_index]:
                    next_index+=1
                    if next_index==len(s2):
                        next_index=0
                        s2_rep+=1
            print next_index,s1_rep,s2_rep
            if next_index in rep_count:
                #found loop 
                prev_s1_rep,prev_s2_rep=rep_count[next_index]
                interval=s1_rep-prev_s1_rep #length of loop
                repeats=(n1-prev_s1_rep)/interval #number of loops 
                res=repeats*(s2_rep-prev_s2_rep) #first find the number of s2 in all the loops 
                remain_s1_rep=(n1-prev_s1_rep)%interval+prev_s1_rep #number of repetitions not in the loops 
                for key,val in rep_count.iteritems():
                    if val[0]==remain_s1_rep:
                        res+=val[1]
                        break
                return res/n2
            
            else: 
                rep_count[next_index]=(s1_rep,s2_rep)
        return s2_rep/n2
                        
                
            
            
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容