LeetCode 题解工作台

将字符串翻转到单调递增

如果一个二进制字符串,是以一些 0 (可能没有 0 )后面跟着一些 1 (也可能没有 1 )的形式组成的,那么该字符串是 单调递增 的。 给你一个二进制字符串 s ,你可以将任何 0 翻转为 1 或者将 1 翻转为 0 。 返回使 s 单调递增的最小翻转次数。 示例 1: 输入: s = "0011…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

我们可以先统计字符串 中 的个数,记为 。定义一个答案变量 ,初始时 $ans = tot$,表示将所有 变成 的翻转次数。 然后,我们可以枚举每个位置 ,将位置 及其左边的所有 变成 ,将位置 右边的所有 变成 ,计算这种情况下的翻转次数,即 $i + 1 - cur + tot - cur$,其中 表示位置 及其左边的 的个数,更新答案 $ans = \min(ans, …

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

如果一个二进制字符串,是以一些 0(可能没有 0)后面跟着一些 1(也可能没有 1)的形式组成的,那么该字符串是 单调递增 的。

给你一个二进制字符串 s,你可以将任何 0 翻转为 1 或者将 1 翻转为 0

返回使 s 单调递增的最小翻转次数。

 

示例 1:

输入:s = "00110"
输出:1
解释:翻转最后一位得到 00111.

示例 2:

输入:s = "010110"
输出:2
解释:翻转得到 011111,或者是 000111。

示例 3:

输入:s = "00011000"
输出:2
解释:翻转得到 00000000。

 

提示:

  • 1 <= s.length <= 105
  • s[i]'0''1'
lightbulb

解题思路

方法一:前缀和 + 枚举

我们可以先统计字符串 ss00 的个数,记为 tottot。定义一个答案变量 ansans,初始时 ans=totans = tot,表示将所有 00 变成 11 的翻转次数。

然后,我们可以枚举每个位置 ii,将位置 ii 及其左边的所有 11 变成 00,将位置 ii 右边的所有 00 变成 11,计算这种情况下的翻转次数,即 i+1cur+totcuri + 1 - cur + tot - cur,其中 curcur 表示位置 ii 及其左边的 00 的个数,更新答案 ans=min(ans,i+1cur+totcur)ans = \min(ans, i + 1 - cur + tot - cur)

最后返回答案 ansans 即可。

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

1
2
3
4
5
6
7
8
9
class Solution:
    def minFlipsMonoIncr(self, s: str) -> int:
        tot = s.count("0")
        ans, cur = tot, 0
        for i, c in enumerate(s, 1):
            cur += int(c == "0")
            ans = min(ans, i - cur + tot - cur)
        return ans
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Candidate should demonstrate a solid understanding of dynamic programming, especially state transitions.

  • question_mark

    Look for understanding of space optimization techniques in dynamic programming problems.

  • question_mark

    Candidate should discuss the importance of minimizing flip operations and trade-offs involved in the solution approach.

warning

常见陷阱

外企场景
  • error

    Failing to optimize space complexity by keeping unnecessary state values.

  • error

    Confusing the problem with one where no flips are allowed, missing the need for careful state transitions.

  • error

    Not correctly accounting for the two possible states ('0' end or '1' end) during the iteration, leading to incorrect results.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider variations with larger binary strings where optimized space handling is critical.

  • arrow_right_alt

    Extend the problem by introducing additional operations, such as flipping multiple characters at once.

  • arrow_right_alt

    Add constraints where the number of flips allowed is limited, adding complexity to the dynamic programming approach.

help

常见问题

外企场景

将字符串翻转到单调递增题解:状态·转移·动态规划 | LeetCode #926 中等