LeetCode 题解工作台
交换字符使得字符串相同
有两个长度相同的字符串 s1 和 s2 ,且它们其中 只含有 字符 "x" 和 "y" ,你需要通过「交换字符」的方式使这两个字符串相同。 每次「交换字符」的时候,你都可以在两个字符串中各选一个字符进行交换。 交换只能发生在两个不同的字符串之间,绝对不能发生在同一个字符串内部。也就是说,我们可以交换…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
根据题目描述,两个字符串 和 都只包含字符 和 ,且长度相同,因此可以将 和 中的字符一一对应起来,即 和 。 如果 $s_1[i] = s_2[i]$,则不需要交换,直接跳过即可。如果 $s_1[i] \neq s_2[i]$,则需要交换,我们统计 和 的组合情况,即 $s_1[i] = x$ 且 $s_2[i] = y$ 的情况,记为 ,对于 $s_1[i] = y$ 且 $s…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
有两个长度相同的字符串 s1 和 s2,且它们其中 只含有 字符 "x" 和 "y",你需要通过「交换字符」的方式使这两个字符串相同。
每次「交换字符」的时候,你都可以在两个字符串中各选一个字符进行交换。
交换只能发生在两个不同的字符串之间,绝对不能发生在同一个字符串内部。也就是说,我们可以交换 s1[i] 和 s2[j],但不能交换 s1[i] 和 s1[j]。
最后,请你返回使 s1 和 s2 相同的最小交换次数,如果没有方法能够使得这两个字符串相同,则返回 -1 。
示例 1:
输入:s1 = "xx", s2 = "yy" 输出:1 解释: 交换 s1[0] 和 s2[1],得到 s1 = "yx",s2 = "yx"。
示例 2:
输入:s1 = "xy", s2 = "yx" 输出:2 解释: 交换 s1[0] 和 s2[0],得到 s1 = "yy",s2 = "xx" 。 交换 s1[0] 和 s2[1],得到 s1 = "xy",s2 = "xy" 。 注意,你不能交换 s1[0] 和 s1[1] 使得 s1 变成 "yx",因为我们只能交换属于两个不同字符串的字符。
示例 3:
输入:s1 = "xx", s2 = "xy" 输出:-1
提示:
1 <= s1.length, s2.length <= 1000s1.length == s2.lengths1, s2只包含'x'或'y'。
解题思路
方法一:贪心
根据题目描述,两个字符串 和 都只包含字符 和 ,且长度相同,因此可以将 和 中的字符一一对应起来,即 和 。
如果 ,则不需要交换,直接跳过即可。如果 ,则需要交换,我们统计 和 的组合情况,即 且 的情况,记为 ,对于 且 的情况,记为 。
如果 为奇数,则无法完成交换,返回 。如果 为偶数,则需要交换的次数为 + + + 。
时间复杂度 ,其中 为字符串 和 的长度。空间复杂度 。
class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
xy = yx = 0
for a, b in zip(s1, s2):
xy += a < b
yx += a > b
if (xy + yx) % 2:
return -1
return xy // 2 + yx // 2 + xy % 2 + yx % 2
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidates should demonstrate an understanding of greedy algorithms and invariant validation.
- question_mark
Look for an ability to handle edge cases like unequal counts of 'x' or 'y' in the two strings.
- question_mark
Candidates who struggle with the swap count calculation or the impossibility check may need further guidance.
常见陷阱
外企场景- error
Failing to check for the basic condition of equal 'x' and 'y' counts in both strings, which leads to unnecessary work or incorrect answers.
- error
Overcomplicating the swap logic or not considering the invariant validation that matches mismatched pairs correctly.
- error
Not properly handling edge cases where strings are already equal or impossible to solve.
进阶变体
外企场景- arrow_right_alt
Strings of larger lengths, requiring optimization of the greedy approach.
- arrow_right_alt
Introducing characters beyond 'x' and 'y' and extending the logic to handle more characters.
- arrow_right_alt
Modifying the problem to allow swapping within the same string.