LeetCode 题解工作台
构成交替字符串需要的最小交换次数
给你一个二进制字符串 s ,现需要将其转化为一个 交替字符串 。请你计算并返回转化所需的 最小 字符交换次数,如果无法完成转化,返回 -1 。 交替字符串 是指:相邻字符之间不存在相等情况的字符串。例如,字符串 "010" 和 "1010" 属于交替字符串,但 "0100" 不是。 任意两个字符都可…
2
题型
6
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
我们先统计字符串 中字符 和字符 的个数,分别记为 和 。 如果 和 的绝对值大于 ,那么无法构成交替字符串,返回 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个二进制字符串 s ,现需要将其转化为一个 交替字符串 。请你计算并返回转化所需的 最小 字符交换次数,如果无法完成转化,返回 -1 。
交替字符串 是指:相邻字符之间不存在相等情况的字符串。例如,字符串 "010" 和 "1010" 属于交替字符串,但 "0100" 不是。
任意两个字符都可以进行交换,不必相邻 。
示例 1:
输入:s = "111000" 输出:1 解释:交换位置 1 和 4:"111000" -> "101010" ,字符串变为交替字符串。
示例 2:
输入:s = "010" 输出:0 解释:字符串已经是交替字符串了,不需要交换。
示例 3:
输入:s = "1110" 输出:-1
提示:
1 <= s.length <= 1000s[i]的值为'0'或'1'
解题思路
方法一:计数
我们先统计字符串 中字符 和字符 的个数,分别记为 和 。
如果 和 的绝对值大于 ,那么无法构成交替字符串,返回 。
如果 和 相等,那么我们可以分别计算将字符串转化为以 开头和以 开头的交替字符串所需要的交换次数,取最小值。
如果 和 不相等,那么我们只需要计算将字符串转化为以字符个数较多的字符开头的交替字符串所需要的交换次数。
问题转换为:计算字符串 转化为以字符 开头的交替字符串所需要的交换次数。
我们定义一个函数 ,表示将字符串 转化为以字符 开头的交替字符串所需要的交换次数。我们遍历字符串 ,对于每个位置 ,如果 与 的奇偶性不同,那么我们需要交换这个位置的字符,计数器 。由于每次交换都会使两个位置的字符变得相同,因此最终的交换次数为计数器的一半。
时间复杂度 ,其中 是字符串 的长度。空间复杂度 。
class Solution:
def minSwaps(self, s: str) -> int:
def calc(c: int) -> int:
return sum((c ^ i & 1) != x for i, x in enumerate(map(int, s))) // 2
n0 = s.count("0")
n1 = len(s) - n0
if abs(n0 - n1) > 1:
return -1
if n0 == n1:
return min(calc(0), calc(1))
return calc(0 if n0 > n1 else 1)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on the approach for checking mismatches against the two alternating patterns, with an optimal solution typically having O(n) time complexity where n is the string length. The space complexity is O(1) since no additional space is needed beyond counters and indices. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Checks the candidate's ability to use greedy methods for string manipulation problems.
- question_mark
Evaluates the candidate's understanding of balancing and invariants in algorithms.
- question_mark
Assesses whether the candidate can validate edge cases like impossible transformations.
常见陷阱
外企场景- error
Forgetting to check if the number of '0's and '1's are balanced, which would make it impossible to alternate the string.
- error
Overcomplicating the solution by using nested loops or additional data structures where a greedy approach suffices.
- error
Not correctly counting mismatches for both alternating patterns before calculating the swaps.
进阶变体
外企场景- arrow_right_alt
Given a larger binary string, how would your approach scale in terms of time and space complexity?
- arrow_right_alt
How can you optimize for different problem constraints, such as limiting the number of swaps or providing feedback on swap validity?
- arrow_right_alt
What happens if the string has an even number of characters, but still cannot be made alternating?