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
466. Count The Repetitions
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Day 12 神句文档 The team contends that these bear more than a...