题目浅析

  • 想查看原题可以点击题目链接

  • 简单地说,就是给两个字符串,求一个字符串到另一个字符串的切换距离。所谓切换距离就不在此赘述,总之就是每个字符变换到另一个小写字母的数值和。

思路分享

代码解答(强烈建议自行解答后再看)

  • 参考题解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def shiftDistance(self, s: str, t: str, nextCost: List[int], previousCost: List[int]) -> int:
s_next = list(accumulate(nextCost+nextCost, initial=0))
s_pre = list(accumulate(previousCost+previousCost, initial=0))

ans = 0
ord_a = ord('a')
for x, y in zip(s, t):
x = ord(x) - ord_a
y = ord(y) - ord_a
ans += min(s_next[y+26 if y < x else y] - s_next[x],
s_pre[(x+26 if x < y else x)+1] - s_pre[y+1])

return ans