1320. Minimum Distance to Type a Word Using Two Fingers

87 篇文章 0 订阅

You have a keyboard layout as shown above in the XY plane, where each English uppercase letter is located at some coordinate, for example, the letter A is located at coordinate (0,0), the letter B is located at coordinate (0,1), the letter P is located at coordinate (2,3) and the letter Z is located at coordinate (4,1).

Given the string word, return the minimum total distance to type such string using only two fingers. The distance between coordinates (x1,y1) and (x2,y2) is |x1 - x2| + |y1 - y2|

Note that the initial positions of your two fingers are considered free so don't count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.

 

Example 1:

Input: word = "CAKE"
Output: 3
Explanation: 
Using two fingers, one optimal way to type "CAKE" is: 
Finger 1 on letter 'C' -> cost = 0 
Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2 
Finger 2 on letter 'K' -> cost = 0 
Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1 
Total distance = 3

Example 2:

Input: word = "HAPPY"
Output: 6
Explanation: 
Using two fingers, one optimal way to type "HAPPY" is:
Finger 1 on letter 'H' -> cost = 0
Finger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2
Finger 2 on letter 'P' -> cost = 0
Finger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0
Finger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4
Total distance = 6

Example 3:

Input: word = "NEW"
Output: 3

Example 4:

Input: word = "YEAR"
Output: 7

 

Constraints:

  • 2 <= word.length <= 300
  • Each word[i] is an English uppercase letter.

思路:dp[idx][i][j]表示打完第idx个字时,双手处于ij位置需要的最小位移。

用滚动数组优化后的代码如下

class Solution(object):
    def minimumDistance(self, word):
        """
        :type word: str
        :rtype: int
        """
        def dist(a, b):
            if a == 0: return 0
            return abs(a//6-b//6)+abs(a%6-b%6)

        INF = 9999999
        dp1, dp2 = {(0,0):0}, {}
        for c in word:
            c = ord(c) + 1
            for a,b in dp1:
                dp2[(a, c)] = min(dp2.get((a, c), INF), dp1.get((a, b), INF) + dist(b, c))
                dp2[(c, b)] = min(dp2.get((c, b), INF), dp1.get((a, b), INF) + dist(a, c))
            dp1,dp2 = dp2, {}

        return min(dp1.values())


s=Solution()
print(s.minimumDistance('CAKE'))
print(s.minimumDistance('HAPPY'))
print(s.minimumDistance('NEW'))
print(s.minimumDistance('YEAR'))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值