LeetCode 题解工作台
最少的后缀翻转次数
给你一个长度为 n 、下标从 0 开始的二进制字符串 target 。你自己有另一个长度为 n 的二进制字符串 s ,最初每一位上都是 0 。你想要让 s 和 target 相等。 在一步操作,你可以选择下标 i ( 0 )并翻转在 闭区间 [i, n - 1] 内的所有位。翻转意味着 '0' 变为…
2
题型
6
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
我们从左到右遍历字符串 ,用变量 记录翻转次数。 当遍历到下标 时,如果当前的翻转次数 的奇偶性与 不同,则需要在下标 处进行一次翻转操作,将 加 。 时间复杂度 ,其中 是字符串的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个长度为 n 、下标从 0 开始的二进制字符串 target 。你自己有另一个长度为 n 的二进制字符串 s ,最初每一位上都是 0 。你想要让 s 和 target 相等。
在一步操作,你可以选择下标 i(0 <= i < n)并翻转在 闭区间 [i, n - 1] 内的所有位。翻转意味着 '0' 变为 '1' ,而 '1' 变为 '0' 。
返回使 s 与 target 相等需要的最少翻转次数。
示例 1:
输入:target = "10111" 输出:3 解释:最初,s = "00000" 。 选择下标 i = 2: "00000" -> "00111" 选择下标 i = 0: "00111" -> "11000" 选择下标 i = 1: "11000" -> "10111" 要达成目标,需要至少 3 次翻转。
示例 2:
输入:target = "101" 输出:3 解释:最初,s = "000" 。 选择下标 i = 0: "000" -> "111" 选择下标 i = 1: "111" -> "100" 选择下标 i = 2: "100" -> "101" 要达成目标,需要至少 3 次翻转。
示例 3:
输入:target = "00000" 输出:0 解释:由于 s 已经等于目标,所以不需要任何操作
提示:
n == target.length1 <= n <= 105target[i]为'0'或'1'
解题思路
方法一:贪心
我们从左到右遍历字符串 ,用变量 记录翻转次数。 当遍历到下标 时,如果当前的翻转次数 的奇偶性与 不同,则需要在下标 处进行一次翻转操作,将 加 。
时间复杂度 ,其中 是字符串的长度。空间复杂度 。
class Solution:
def minFlips(self, target: str) -> int:
ans = 0
for v in target:
if (ans & 1) ^ int(v):
ans += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates an understanding of greedy algorithms by applying it to string manipulation.
- question_mark
Candidate proposes a solution with O(n) time complexity, which is optimal for this problem.
- question_mark
Candidate identifies and implements the invariant validation effectively, minimizing the number of operations.
常见陷阱
外企场景- error
Failing to track the flip count correctly, leading to unnecessary operations or missed flips.
- error
Overcomplicating the solution by trying to optimize beyond the greedy approach, which is already optimal.
- error
Misunderstanding the effect of each flip and failing to track its impact correctly on the string.
进阶变体
外企场景- arrow_right_alt
Consider extending the problem to include different types of strings, such as strings with characters other than '0' and '1'.
- arrow_right_alt
Explore the impact of reverse operations, where flips are performed from right to left instead of left to right.
- arrow_right_alt
Modify the problem to consider minimizing the number of flips, but with constraints on the number of flips allowed per operation.