8.22 - hard - 89

466. Count The Repetitions
这题好困难,看了答案也很难理解,估计只能背答案了。。。等复习的时候再来做一次。

class Solution(object):
     def getMaxRepetitions(self, s1, n1, s2, n2):

        if any(c for c in set(s2) if c not in set(s1)):   # early return if impossible
            return 0

        s2_index_to_reps = {0 : (0, 0)}   # mapping from index in s2 to numbers of repetitions of s1 and s2
        i, j = 0, 0
        s1_reps, s2_reps = 0, 0

        while s1_reps < n1:

            if s1[i] == s2[j]:
                j += 1     # move s2 pointer if chars match
            i += 1

            if j == len(s2):
                j = 0
                s2_reps += 1

            if i == len(s1):
                i = 0
                s1_reps += 1
                if j in s2_index_to_reps:   # loop found, same index in s2 as seen before
                    break
                s2_index_to_reps[j] = (s1_reps, s2_reps)

        if s1_reps == n1:    # already used n1 copies of s1
            return s2_reps // n2
        # 完整的x个s1可以循环到y个s2,最后结束的地方是s2[j]
        initial_s1_reps, initial_s2_reps = s2_index_to_reps[j]    # repetitions before loop starts
        loop_s1_reps = s1_reps - initial_s1_reps # 计算每一个整loop,需要多少个s1
        loop_s2_reps = s2_reps - initial_s2_reps
        loops = (n1 - initial_s1_reps) // loop_s1_reps

        s2_reps = initial_s2_reps + loops * loop_s2_reps
        s1_reps = initial_s1_reps + loops * loop_s1_reps

        while s1_reps < n1:   # if loop does not end with n1 copies of s1, keep going

            if s1[i] == s2[j]:
                j += 1
            i += 1

            if i == len(s1):
                i = 0
                s1_reps += 1

            if j == len(s2):
                j = 0
                s2_reps += 1

        return s2_reps // n2
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,916评论 0 33
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 179,029评论 25 709
  • 约定了地点,见到了她,她说来的路上摔到了,心疼,幸好不严重,可能是看到我很激动吧,微笑。 去嘉惠美转了一圈,买了点...
    听雷雷说阅读 191评论 0 0
  • 我知道我最近的时间都去哪儿了。 已经n多年没有追过国产剧的我,当了好一段日子的追剧狗,一部,接着一部,很忠诚,所有...
    敢不敢笑一个阅读 806评论 1 1
  • 每个人有自己要走的路 是否应该继续沉默 尝试着找回原来的那种感觉 迷茫,烦,乱 沉默到低头 沪这个城市的天气,阴沉...
    阿Q三少阅读 181评论 0 0

友情链接更多精彩内容