LeetCode 题解工作台
K 次操作转变字符串
给你两个字符串 s 和 t ,你的目标是在 k 次操作以内把字符串 s 转变成 t 。 在第 i 次操作时( 1 ),你可以选择进行如下操作: 选择字符串 s 中满足 1 且之前未被选过的任意下标 j (下标从 1 开始),并将此位置的字符切换 i 次。 不进行任何操作。 切换 1 个字符的意思是用…
2
题型
4
代码语言
3
相关题
当前训练重点
中等 · 哈希·表·结合·string
答案摘要
我们首先判断字符串 和字符串 的长度是否相等,如果不相等,直接返回 `false`。 如果相等,我们可以统计每个位置的字符需要操作的最小次数,即 表示最小操作次数为 的字符的个数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
给你两个字符串 s 和 t ,你的目标是在 k 次操作以内把字符串 s 转变成 t 。
在第 i 次操作时(1 <= i <= k),你可以选择进行如下操作:
- 选择字符串
s中满足1 <= j <= s.length且之前未被选过的任意下标j(下标从 1 开始),并将此位置的字符切换i次。 - 不进行任何操作。
切换 1 个字符的意思是用字母表中该字母的下一个字母替换它(字母表环状接起来,所以 'z' 切换后会变成 'a')。第 i 次操作意味着该字符应切换 i 次
请记住任意一个下标 j 最多只能被操作 1 次。
如果在不超过 k 次操作内可以把字符串 s 转变成 t ,那么请你返回 true ,否则请你返回 false 。
示例 1:
输入:s = "input", t = "ouput", k = 9 输出:true 解释:第 6 次操作时,我们将 'i' 切换 6 次得到 'o' 。第 7 次操作时,我们将 'n' 切换 7 次得到 'u' 。
示例 2:
输入:s = "abc", t = "bcd", k = 10 输出:false 解释:我们需要将每个字符切换 1 次才能得到 t 。我们可以在第 1 次操作时将 'a' 切换成 'b' ,但另外 2 个字母在剩余操作中无法再转变为 t 中对应字母。
示例 3:
输入:s = "aab", t = "bbb", k = 27 输出:true 解释:第 1 次操作时,我们将第一个 'a' 切换 1 次得到 'b' 。在第 27 次操作时,我们将第二个字母 'a' 切换 27 次得到 'b' 。
提示:
1 <= s.length, t.length <= 10^50 <= k <= 10^9s和t只包含小写英文字母。
解题思路
方法一:计数
我们首先判断字符串 和字符串 的长度是否相等,如果不相等,直接返回 false。
如果相等,我们可以统计每个位置的字符需要操作的最小次数,即 表示最小操作次数为 的字符的个数。
如果有 个字符需要操作 次,那么我们需要 次操作才能将这些字符转换为 中对应的字符。因此,我们在 xx + 26 \times (cnt[x] - 1) \gt kt$ 中对应的字符,返回 false。
否则,枚举结束后,说明我们可以将所有字符转换为 中对应的字符,返回 true。
时间复杂度 ,空间复杂度 ,其中 为字符串 和 的长度;而 为字符集大小,本题中 。
class Solution:
def canConvertString(self, s: str, t: str, k: int) -> bool:
if len(s) != len(t):
return False
cnt = [0] * 26
for a, b in zip(s, t):
x = (ord(b) - ord(a) + 26) % 26
cnt[x] += 1
for i in range(1, 26):
if i + 26 * (cnt[i] - 1) > k:
return False
return True
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) for iterating over s and t and updating the hash table, where n is the string length. Space complexity is O(26) = O(1) for the shift frequency hash table, independent of n. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The problem tests the ability to use a hash table for counting frequencies of required character shifts.
- question_mark
Watch for off-by-one errors in calculating alphabet shifts with wrap-around from 'z' to 'a'.
- question_mark
Efficiently handling repeated shifts using multiples of 26 is key to staying within k moves.
常见陷阱
外企场景- error
Failing to consider wrap-around shifts correctly, e.g., 'z' to 'a' as one move.
- error
Not accounting for multiple characters needing the same shift, causing move count overflow.
- error
Assuming shifts beyond k are valid without scheduling repeated shifts in multiples of 26.
进阶变体
外企场景- arrow_right_alt
Allow backward shifts and check if s can convert to t in k moves using positive and negative shifts.
- arrow_right_alt
Limit the alphabet to a subset and verify conversion feasibility within k moves for constrained letters.
- arrow_right_alt
Introduce variable move costs for different characters and determine if s can convert to t within total cost k.