8.23 - hard - 98

514. Freedom Trail

手写了TLE版本,加了一些memory,不过还是TLE。基本思路是对的,只是有一点问题,不用找到所有的值,只需要针对某一个index,找到之前的第一个和之后的第一个就可以了。

class Solution(object):
    def findRotateSteps(self, ring, key):
        """
        :type ring: str
        :type key: str
        :rtype: int
        """
        ring = list(ring)
        return self.search(ring, key, 0, {}) + len(key)
        
    
    def search(self, ring, key, pos, m):
        if pos == len(key):
            return 0
        if str(ring)+str(pos) in m:
            return m[str(ring)+str(pos)]
        res = sys.maxint
        for i in range(len(ring)):
            if ring[i] == key[pos]:
                new_ring = ring[i:] + ring[:i]
                res = min(res, self.search(new_ring, key, pos + 1, m)+min(i, len(ring)-i))
        m[str(ring)+str(pos)] = res
        return res
class Solution(object):
    def findRotateSteps(self, ring, key):
        """
        :type ring: str
        :type key: str
        :rtype: int
        """
        if not ring or not key:
            return 0
        mem = [[0 for _ in range(len(key))] for _ in range(len(ring))]
        return self.findShortest(ring, 0, key, 0, mem)
    
    def findShortest(self, arr, p, key, pos, mem):
        if pos == len(key):
            return 0
        if mem[p][pos] > 0:
            return mem[p][pos]
        c1 = c2 = 0
        i = j = p
        # from pericular position of p, find 
        while arr[i] != key[pos]:
            i = (i+1) % len(arr)
            c1 += 1
            
        while arr[j] != key[pos]:
            j= (j-1+len(arr)) % len(arr)
            c2 += 1
        r1 = self.findShortest(arr, i, key, pos+1, mem) + c1 + 1
        r2 = self.findShortest(arr, j, key, pos+1, mem) + c2 + 1
        mem[p][pos] = min(r1,r2)
        return mem[p][pos]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,560评论 25 708
  • 一、源题QUESTION 36Your database is open and the LISTENER lis...
    猫猫_tomluo阅读 1,286评论 0 2
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,779评论 0 33
  • 有时,望着眼前的平静的一切,我会害怕!回首过去数年,日子都太过平静,还没经历多少苦难,可人生哪有那么容易让你过,我...
    木易allie阅读 185评论 0 1
  • 我不记得昨天晚上梦到了什么,只是早晨起床画眉时,突然很想秦哲,以至于画的一团遭,还迟到了20分钟。 我总是认为秦哲...
    如果玻璃会说话z阅读 360评论 0 0