LeetCode 题解工作台
使二进制字符串字符交替的最少反转次数
给你一个二进制字符串 s 。你可以按任意顺序执行以下两种操作任意次: 类型 1 :删除 字符串 s 的第一个字符并将它 添加 到字符串结尾。 类型 2 :选择 字符串 s 中任意一个字符并将该字符 反转 ,也就是如果值为 '0' ,则反转得到 '1' ,反之亦然。 请你返回使 s 变成 交替 字符串…
3
题型
8
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们注意到,操作 的作用实际上是让字符串成为一个环,而操作 是使得环中的一段长度为 的子串变成交替二进制串。 因此,我们只需要枚举每个长度为 的子串,计算将其变成交替二进制串的代价,取最小值即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个二进制字符串 s 。你可以按任意顺序执行以下两种操作任意次:
- 类型 1 :删除 字符串
s的第一个字符并将它 添加 到字符串结尾。 - 类型 2 :选择 字符串
s中任意一个字符并将该字符 反转 ,也就是如果值为'0',则反转得到'1',反之亦然。
请你返回使 s 变成 交替 字符串的前提下, 类型 2 的 最少 操作次数 。
我们称一个字符串是 交替 的,需要满足任意相邻字符都不同。
- 比方说,字符串
"010"和"1010"都是交替的,但是字符串"0100"不是。
示例 1:
输入:s = "111000" 输出:2 解释:执行第一种操作两次,得到 s = "100011" 。 然后对第三个和第六个字符执行第二种操作,得到 s = "101010" 。
示例 2:
输入:s = "010" 输出:0 解释:字符串已经是交替的。
示例 3:
输入:s = "1110" 输出:1 解释:对第二个字符执行第二种操作,得到 s = "1010" 。
提示:
1 <= s.length <= 105s[i]要么是'0',要么是'1'。
解题思路
方法一:滑动窗口
我们注意到,操作 的作用实际上是让字符串成为一个环,而操作 是使得环中的一段长度为 的子串变成交替二进制串。
因此,我们只需要枚举每个长度为 的子串,计算将其变成交替二进制串的代价,取最小值即可。
我们可以预先计算出字符串 与两种交替二进制串的差异数量,记为 ,则将 变成第一种交替二进制串的代价为 ,将 变成第二种交替二进制串的代价为 。我们初始化 。
接下来,我们枚举每个长度为 的子串,更新 的值。对于每个位置 ,我们将 从第一种交替二进制串的差异数量中减去,并将 加入到第二种交替二进制串的差异数量中。更新 。
最后返回 即可。
时间复杂度 ,其中 是字符串的长度。空间复杂度 。
class Solution:
def minFlips(self, s: str) -> int:
n = len(s)
target = "01"
cnt = sum(c != target[i & 1] for i, c in enumerate(s))
ans = min(cnt, n - cnt)
for i in range(n):
cnt -= s[i] != target[i & 1]
cnt += s[i] != target[(i + n) & 1]
ans = min(ans, cnt, n - cnt)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for understanding of state transitions and their optimization in a string manipulation context.
- question_mark
Check if the candidate can connect dynamic programming principles with practical application, especially in minimizing operations.
- question_mark
Assess whether the candidate focuses on the efficiency of the algorithm, especially for large input sizes.
常见陷阱
外企场景- error
Failing to recognize the importance of tracking odd and even positions separately can lead to inefficient solutions.
- error
Not optimizing for large strings may result in time complexity that doesn't meet the problem's constraints.
- error
Overcomplicating the solution with unnecessary operations can lead to excessive space or time complexity.
进阶变体
外企场景- arrow_right_alt
Consider variants where the string contains characters other than '0' and '1', such as binary sequences with additional symbols.
- arrow_right_alt
Adapt the problem to consider non-binary strings where adjacent characters must still differ, like alternating colors in a grid.
- arrow_right_alt
Change the problem to allow more complex operations, such as flipping multiple bits at once or limiting the number of allowed flips.