LeetCode 题解工作台

最少的后缀翻转次数

给你一个长度为 n 、下标从 0 开始的二进制字符串 target 。你自己有另一个长度为 n 的二进制字符串 s ,最初每一位上都是 0 。你想要让 s 和 target 相等。 在一步操作,你可以选择下标 i ( 0 )并翻转在 闭区间 [i, n - 1] 内的所有位。翻转意味着 '0' 变为…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

我们从左到右遍历字符串 ,用变量 记录翻转次数。 当遍历到下标 时,如果当前的翻转次数 的奇偶性与 不同,则需要在下标 处进行一次翻转操作,将 加 。 时间复杂度 ,其中 是字符串的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个长度为 n 、下标从 0 开始的二进制字符串 target 。你自己有另一个长度为 n 的二进制字符串 s ,最初每一位上都是 0 。你想要让 starget 相等。

在一步操作,你可以选择下标 i0 <= 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.length
  • 1 <= n <= 105
  • target[i]'0''1'
lightbulb

解题思路

方法一:贪心

我们从左到右遍历字符串 target\textit{target},用变量 ans\textit{ans} 记录翻转次数。 当遍历到下标 ii 时,如果当前的翻转次数 ans\textit{ans} 的奇偶性与 target[i]\textit{target}[i] 不同,则需要在下标 ii 处进行一次翻转操作,将 ans\textit{ans}11

时间复杂度 O(n)O(n),其中 nn 是字符串的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
class Solution:
    def minFlips(self, target: str) -> int:
        ans = 0
        for v in target:
            if (ans & 1) ^ int(v):
                ans += 1
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

最少的后缀翻转次数题解:贪心·invariant | LeetCode #1529 中等