LeetCode 题解工作台

将 1 移动到末尾的最大操作次数

给你一个 二进制字符串 s 。 你可以对这个字符串执行 任意次 下述操作: 选择字符串中的任一下标 i ( i + 1 ),该下标满足 s[i] == '1' 且 s[i + 1] == '0' 。 将字符 s[i] 向 右移 直到它到达字符串的末端或另一个 '1' 。例如,对于 s = "0100…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

我们用一个变量 记录答案,用一个变量 记录当前的 的个数。 然后我们遍历字符串 ,如果当前字符是 ,则 加一,否则如果存在前一个字符,且前一个字符是 ,那么前面的 个 可以往后移动,答案加上 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个 二进制字符串 s

你可以对这个字符串执行 任意次 下述操作:

  • 选择字符串中的任一下标 ii + 1 < s.length ),该下标满足 s[i] == '1's[i + 1] == '0'
  • 将字符 s[i]右移 直到它到达字符串的末端或另一个 '1'。例如,对于 s = "010010",如果我们选择 i = 1,结果字符串将会是 s = "000110"

返回你能执行的 最大 操作次数。

 

示例 1:

输入: s = "1001101"

输出: 4

解释:

可以执行以下操作:

  • 选择下标 i = 0。结果字符串为 s = "0011101"
  • 选择下标 i = 4。结果字符串为 s = "0011011"
  • 选择下标 i = 3。结果字符串为 s = "0010111"
  • 选择下标 i = 2。结果字符串为 s = "0001111"

示例 2:

输入: s = "00111"

输出: 0

 

提示:

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

解题思路

方法一:贪心

我们用一个变量 ans\textit{ans} 记录答案,用一个变量 cnt\textit{cnt} 记录当前的 11 的个数。

然后我们遍历字符串 ss,如果当前字符是 11,则 cnt\textit{cnt} 加一,否则如果存在前一个字符,且前一个字符是 11,那么前面的 cnt\textit{cnt}11 可以往后移动,答案加上 cnt\textit{cnt}

最后返回答案即可。

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

1
2
3
4
5
6
7
8
9
10
class Solution:
    def maxOperations(self, s: str) -> int:
        ans = cnt = 0
        for i, c in enumerate(s):
            if c == "1":
                cnt += 1
            elif i and s[i - 1] == "1":
                ans += cnt
        return ans
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    The candidate demonstrates an understanding of greedy algorithms by explaining the choice of selecting the leftmost '1'.

  • question_mark

    The candidate should discuss the trade-offs of swapping earlier versus later '1's, as this maximizes operations.

  • question_mark

    The candidate should be able to articulate the time and space complexity for their solution.

warning

常见陷阱

外企场景
  • error

    Misunderstanding the operation by performing swaps in non-greedy orders, reducing the number of valid operations.

  • error

    Not considering edge cases where no operations are possible, such as when all '1's are already at the end of the string.

  • error

    Failing to optimize for time complexity when implementing the solution, leading to inefficient algorithms.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Handling strings with only '0's or only '1's.

  • arrow_right_alt

    Allowing a fixed number of operations rather than maximizing the count.

  • arrow_right_alt

    Changing the operation such that you can only swap a fixed number of '1's.

help

常见问题

外企场景

将 1 移动到末尾的最大操作次数题解:贪心·invariant | LeetCode #3228 中等