LeetCode 题解工作台
消除相邻近似相等字符
给你一个下标从 0 开始的字符串 word 。 一次操作中,你可以选择 word 中任意一个下标 i ,将 word[i] 修改成任意一个小写英文字母。 请你返回消除 word 中所有相邻 近似相等 字符的 最少 操作次数。 两个字符 a 和 b 如果满足 a == b 或者 a 和 b 在字母表中…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们从下标 开始遍历字符串 ,如果 和 $word[i - 1]$ 相邻近似相等,那么我们就贪心地将 替换成一个与 $word[i - 1]$ 和 $word[i + 1]$ 都不相等的字符(可以不执行替换操作,记录操作次数即可)。然后,我们跳过 $word[i + 1]$,继续遍历字符串 。 最后,我们返回记录的操作次数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个下标从 0 开始的字符串 word 。
一次操作中,你可以选择 word 中任意一个下标 i ,将 word[i] 修改成任意一个小写英文字母。
请你返回消除 word 中所有相邻 近似相等 字符的 最少 操作次数。
两个字符 a 和 b 如果满足 a == b 或者 a 和 b 在字母表中是相邻的,那么我们称它们是 近似相等 字符。
示例 1:
输入:word = "aaaaa" 输出:2 解释:我们将 word 变为 "acaca" ,该字符串没有相邻近似相等字符。 消除 word 中所有相邻近似相等字符最少需要 2 次操作。
示例 2:
输入:word = "abddez" 输出:2 解释:我们将 word 变为 "ybdoez" ,该字符串没有相邻近似相等字符。 消除 word 中所有相邻近似相等字符最少需要 2 次操作。
示例 3:
输入:word = "zyxyxyz" 输出:3 解释:我们将 word 变为 "zaxaxaz" ,该字符串没有相邻近似相等字符。 消除 word 中所有相邻近似相等字符最少需要 3 次操作
提示:
1 <= word.length <= 100word只包含小写英文字母。
解题思路
方法一:贪心
我们从下标 开始遍历字符串 ,如果 和 相邻近似相等,那么我们就贪心地将 替换成一个与 和 都不相等的字符(可以不执行替换操作,记录操作次数即可)。然后,我们跳过 ,继续遍历字符串 。
最后,我们返回记录的操作次数。
时间复杂度 ,其中 是字符串 的长度。空间复杂度 。
class Solution:
def removeAlmostEqualCharacters(self, word: str) -> int:
ans = 0
i, n = 1, len(word)
while i < n:
if abs(ord(word[i]) - ord(word[i - 1])) < 2:
ans += 1
i += 2
else:
i += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Strong understanding of dynamic programming is required to identify and manage state transitions.
- question_mark
Greedy strategies must be applied carefully to ensure optimal character transformations.
- question_mark
The ability to minimize space complexity while solving the problem shows an efficient solution approach.
常见陷阱
外企场景- error
Failing to properly account for all adjacent almost-equal character pairs during transformations can lead to suboptimal solutions.
- error
Incorrect greedy character selection might result in more operations than necessary, especially in longer strings.
- error
Excessive space complexity due to improper state tracking or inefficient memory management can negatively impact performance.
进阶变体
外企场景- arrow_right_alt
Consider variations where the allowed transformations could involve changing characters to any set of characters, not just lowercase English letters.
- arrow_right_alt
Explore the scenario where adjacent characters have varying levels of 'almost-equality,' requiring more complex state transitions.
- arrow_right_alt
Analyze the problem with longer strings, where the dynamic programming approach's time complexity becomes more critical.