LeetCode 题解工作台

二进制字符串重新安排顺序需要的时间

给你一个二进制字符串 s 。在一秒之中, 所有 子字符串 "01" 同时 被替换成 "10" 。这个过程持续进行到没有 "01" 存在。 请你返回完成这个过程所需要的秒数。 示例 1: 输入: s = "0110101" 输出: 4 解释: 一秒后,s 变成 "1011010" 。 再过 1 秒后,…

category

3

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

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

bolt

答案摘要

由于本题数据范围不大,所以可以暴力模拟,每一轮将字符串中所有 “01” 替换为 “10”,统计轮次作为答案。 时间复杂度 。每一轮时间复杂度 ,最多进行 轮操作。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个二进制字符串 s 。在一秒之中,所有 子字符串 "01" 同时 被替换成 "10" 。这个过程持续进行到没有 "01" 存在。

请你返回完成这个过程所需要的秒数。

 

示例 1:

输入:s = "0110101"
输出:4
解释:
一秒后,s 变成 "1011010" 。
再过 1 秒后,s 变成 "1101100" 。
第三秒过后,s 变成 "1110100" 。
第四秒后,s 变成 "1111000" 。
此时没有 "01" 存在,整个过程花费 4 秒。
所以我们返回 4 。

示例 2:

输入:s = "11100"
输出:0
解释:
s 中没有 "01" 存在,整个过程花费 0 秒。
所以我们返回 0 。

 

提示:

  • 1 <= s.length <= 1000
  • s[i] 要么是 '0' ,要么是 '1'

 

进阶:

你能以 O(n) 的时间复杂度解决这个问题吗?

lightbulb

解题思路

方法一:暴力模拟

由于本题数据范围不大,所以可以暴力模拟,每一轮将字符串中所有 “01” 替换为 “10”,统计轮次作为答案。

时间复杂度 O(n2)O(n^2)。每一轮时间复杂度 O(n)O(n),最多进行 nn 轮操作。

1
2
3
4
5
6
7
8
class Solution:
    def secondsToRemoveOccurrences(self, s: str) -> int:
        ans = 0
        while s.count('01'):
            s = s.replace('01', '10')
            ans += 1
        return ans
speed

复杂度分析

指标
时间complexity depends on the approach: direct simulation can reach O(n^2) in worst cases, while tracking positions or DP can achieve O(n). Space complexity ranges from O(n) for storing positions or DP arrays.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate may attempt a naive loop-based simulation first.

  • question_mark

    Look for candidates identifying overlapping flips and simultaneous state changes.

  • question_mark

    Efficient solutions often emerge by tracking 0 positions or using DP to model time steps.

warning

常见陷阱

外企场景
  • error

    Failing to simulate flips simultaneously, leading to incorrect step counts.

  • error

    Ignoring edge cases where the string has no 01 pairs from the start.

  • error

    Using inefficient string concatenations repeatedly, causing performance issues.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Determine time for similar transformations in ternary strings with multiple patterns.

  • arrow_right_alt

    Compute minimal steps if only a single 01 can flip per second instead of all simultaneously.

  • arrow_right_alt

    Count the total number of flips instead of seconds until stabilization.

help

常见问题

外企场景

二进制字符串重新安排顺序需要的时间题解:状态·转移·动态规划 | LeetCode #2380 中等