LeetCode 题解工作台
将 1 移动到末尾的最大操作次数
给你一个 二进制字符串 s 。 你可以对这个字符串执行 任意次 下述操作: 选择字符串中的任一下标 i ( i + 1 ),该下标满足 s[i] == '1' 且 s[i + 1] == '0' 。 将字符 s[i] 向 右移 直到它到达字符串的末端或另一个 '1' 。例如,对于 s = "0100…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
我们用一个变量 记录答案,用一个变量 记录当前的 的个数。 然后我们遍历字符串 ,如果当前字符是 ,则 加一,否则如果存在前一个字符,且前一个字符是 ,那么前面的 个 可以往后移动,答案加上 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个 二进制字符串 s。
你可以对这个字符串执行 任意次 下述操作:
- 选择字符串中的任一下标
i(i + 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 <= 105s[i]为'0'或'1'。
解题思路
方法一:贪心
我们用一个变量 记录答案,用一个变量 记录当前的 的个数。
然后我们遍历字符串 ,如果当前字符是 ,则 加一,否则如果存在前一个字符,且前一个字符是 ,那么前面的 个 可以往后移动,答案加上 。
最后返回答案即可。
时间复杂度 ,其中 为字符串 的长度。空间复杂度 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.