LeetCode 题解工作台
二进制字符串重新安排顺序需要的时间
给你一个二进制字符串 s 。在一秒之中, 所有 子字符串 "01" 同时 被替换成 "10" 。这个过程持续进行到没有 "01" 存在。 请你返回完成这个过程所需要的秒数。 示例 1: 输入: s = "0110101" 输出: 4 解释: 一秒后,s 变成 "1011010" 。 再过 1 秒后,…
3
题型
4
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
由于本题数据范围不大,所以可以暴力模拟,每一轮将字符串中所有 “01” 替换为 “10”,统计轮次作为答案。 时间复杂度 。每一轮时间复杂度 ,最多进行 轮操作。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个二进制字符串 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 <= 1000s[i]要么是'0',要么是'1'。
进阶:
你能以 O(n) 的时间复杂度解决这个问题吗?
解题思路
方法一:暴力模拟
由于本题数据范围不大,所以可以暴力模拟,每一轮将字符串中所有 “01” 替换为 “10”,统计轮次作为答案。
时间复杂度 。每一轮时间复杂度 ,最多进行 轮操作。
class Solution:
def secondsToRemoveOccurrences(self, s: str) -> int:
ans = 0
while s.count('01'):
s = s.replace('01', '10')
ans += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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 |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.