leetcode在力扣 App 中打开
调试中...
调试中...
题目描述
题目描述
题解
题解
提交记录
提交记录
代码
代码
测试用例
测试用例
测试结果
测试结果
中等
相关标签
相关企业
提示

给你两个长度相同的字符串 s 和 t ,以及两个整数数组 nextCost 和 previousCost 。

一次操作中,你可以选择 s 中的一个下标 i ,执行以下操作 之一 :

  • 将 s[i] 切换为字母表中的下一个字母,如果 s[i] == 'z' ,切换后得到 'a' 。操作的代价为 nextCost[j] ,其中 j 表示 s[i] 在字母表中的下标。
  • 将 s[i] 切换为字母表中的上一个字母,如果 s[i] == 'a' ,切换后得到 'z' 。操作的代价为 previousCost[j] ,其中 j 是 s[i] 在字母表中的下标。

切换距离 指的是将字符串 s 变为字符串 t 的 最少 操作代价总和。

请你返回从 s 到 t 的 切换距离 。

 

示例 1:

输入:s = "abab", t = "baba", nextCost = [100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], previousCost = [1,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

输出:2

解释:

  • 选择下标 i = 0 并将 s[0] 向前切换 25 次,总代价为 1 。
  • 选择下标 i = 1 并将 s[1] 向后切换 25 次,总代价为 0 。
  • 选择下标 i = 2 并将 s[2] 向前切换 25 次,总代价为 1 。
  • 选择下标 i = 3 并将 s[3] 向后切换 25 次,总代价为 0 。

示例 2:

输入:s = "leet", t = "code", nextCost = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], previousCost = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]

输出:31

解释:

  • 选择下标 i = 0 并将 s[0] 向前切换 9 次,总代价为 9 。
  • 选择下标 i = 1 并将 s[1] 向后切换 10 次,总代价为 10 。
  • 选择下标 i = 2 并将 s[2] 向前切换 1 次,总代价为 1 。
  • 选择下标 i = 3 并将 s[3] 向后切换 11 次,总代价为 11 。

 

提示:

  • 1 <= s.length == t.length <= 105
  • s 和 t 都只包含小写英文字母。
  • nextCost.length == previousCost.length == 26
  • 0 <= nextCost[i], previousCost[i] <= 109
通过次数
2.8K
提交次数
5.4K
通过率
51.4%


相关企业

提示 1
- For every unordered pair of characters (a, b), the cost of turning a into b is equal to the minimum between:
  • If i < j, nextCost[i] + nextCost[i + 1] + … + nextCost[j - 1], and nextCost[i] + nextCost[i + 1] + … + nextCost[25] + nextCost[0] + … + nextCost[j - 1] otherwise.
  • If i < j, prevCost[i] + prevCost[i - 1] + … + prevCost[0] + prevCost[25] + … + prevCost[j + 1], and prevCost[i] + prevCost[i - 1] + … + prevCost[j + 1] otherwise.
Where i and j are the indices of a and b in the alphabet.

提示 2
The shift distance is the sum of costs of turning s[i] into t[i].

相似题目

评论 (0)

贡献者
© 2025 领扣网络(上海)有限公司
3 人在线
行 1,列 1
s =
"abab"
t =
"baba"
nextCost =
[100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
previousCost =
[1,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Source