LeetCode 题解工作台
使所有字符相等的最小成本
给你一个下标从 0 开始、长度为 n 的二进制字符串 s ,你可以对其执行两种操作: 选中一个下标 i 并且反转从下标 0 到下标 i (包括下标 0 和下标 i )的所有字符,成本为 i + 1 。 选中一个下标 i 并且反转从下标 i 到下标 n - 1 (包括下标 i 和下标 n - 1 )的…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
根据题目描述,如果 $s[i] \neq s[i - 1]$,那么一定要执行操作,否则无法使所有字符相等。 我们要么选择将 的字符全部反转,反转的成本为 ;要么选择将 的字符全部反转,反转的成本为 $n - i$。取两者中的最小值即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个下标从 0 开始、长度为 n 的二进制字符串 s ,你可以对其执行两种操作:
- 选中一个下标
i并且反转从下标0到下标i(包括下标0和下标i)的所有字符,成本为i + 1。 - 选中一个下标
i并且反转从下标i到下标n - 1(包括下标i和下标n - 1)的所有字符,成本为n - i。
返回使字符串内所有字符 相等 需要的 最小成本 。
反转 字符意味着:如果原来的值是 '0' ,则反转后值变为 '1' ,反之亦然。
示例 1:
输入:s = "0011" 输出:2 解释:执行第二种操作,选中下标i = 2,可以得到s = "0000" ,成本为 2。可以证明 2 是使所有字符相等的最小成本。
示例 2:
输入:s = "010101" 输出:9 解释:执行第一种操作,选中下标 i = 2 ,可以得到 s = "101101" ,成本为 3 。 执行第一种操作,选中下标 i = 1 ,可以得到 s = "011101" ,成本为 2 。 执行第一种操作,选中下标 i = 0 ,可以得到 s = "111101" ,成本为 1 。 执行第二种操作,选中下标 i = 4 ,可以得到 s = "111110" ,成本为 2 。 执行第二种操作,选中下标 i = 5 ,可以得到 s = "111111" ,成本为 1 。 使所有字符相等的总成本等于 9 。可以证明 9 是使所有字符相等的最小成本。
提示:
1 <= s.length == n <= 105s[i]为'0'或'1'
解题思路
方法一:贪心
根据题目描述,如果 ,那么一定要执行操作,否则无法使所有字符相等。
我们要么选择将 的字符全部反转,反转的成本为 ;要么选择将 的字符全部反转,反转的成本为 。取两者中的最小值即可。
我们遍历字符串 ,将所有需要反转的字符的成本相加,即可得到最小成本。
时间复杂度 ,其中 为字符串 的长度。空间复杂度 。
class Solution:
def minimumCost(self, s: str) -> int:
ans, n = 0, len(s)
for i in range(1, n):
if s[i] != s[i - 1]:
ans += min(i, n - i)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate efficiently applies dynamic programming principles to minimize the cost.
- question_mark
They effectively manage the complexity of the problem by optimizing calculations for large inputs.
- question_mark
The candidate demonstrates a clear understanding of state transitions and prefix operations for solving the problem.
常见陷阱
外企场景- error
Forgetting to handle the cost calculation at each index and neglecting to track the prefix operations.
- error
Not optimizing the solution for larger inputs, leading to time limit exceed errors.
- error
Confusing the required operations for inverting and calculating prefix costs, leading to incorrect results.
进阶变体
外企场景- arrow_right_alt
The problem can be extended to strings of different characters beyond '0' and '1', requiring a more generalized solution.
- arrow_right_alt
A variation of the problem could involve allowing multiple operations on each character rather than just a prefix change or inversion.
- arrow_right_alt
The cost structure could be modified, such as introducing different costs for different types of operations, changing the problem dynamics.