LeetCode 题解工作台
判断通过操作能否让字符串相等 II
给你两个字符串 s1 和 s2 ,两个字符串长度都为 n ,且只包含 小写 英文字母。 你可以对两个字符串中的 任意一个 执行以下操作 任意 次: 选择两个下标 i 和 j ,满足 i 且 j - i 是 偶数 ,然后 交换 这个字符串中两个下标对应的字符。 如果你可以让字符串 s1 和 s2 相等…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 哈希·表·结合·string
答案摘要
我们观察题目中的操作,可以发现,如果字符串的两个下标 和 的奇偶性相同,那么它们可以通过交换改变顺序。 因此,我们可以统计两个字符串中奇数下标的字符的出现次数,以及偶数下标的字符的出现次数,如果两个字符串的统计结果相同,那么我们就可以通过操作使得两个字符串相等。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
给你两个字符串 s1 和 s2 ,两个字符串长度都为 n ,且只包含 小写 英文字母。
你可以对两个字符串中的 任意一个 执行以下操作 任意 次:
- 选择两个下标
i和j,满足i < j且j - i是 偶数,然后 交换 这个字符串中两个下标对应的字符。
如果你可以让字符串 s1 和 s2 相等,那么返回 true ,否则返回 false 。
示例 1:
输入:s1 = "abcdba", s2 = "cabdab" 输出:true 解释:我们可以对 s1 执行以下操作: - 选择下标 i = 0 ,j = 2 ,得到字符串 s1 = "cbadba" 。 - 选择下标 i = 2 ,j = 4 ,得到字符串 s1 = "cbbdaa" 。 - 选择下标 i = 1 ,j = 5 ,得到字符串 s1 = "cabdab" = s2 。
示例 2:
输入:s1 = "abe", s2 = "bea" 输出:false 解释:无法让两个字符串相等。
提示:
n == s1.length == s2.length1 <= n <= 105s1和s2只包含小写英文字母。
解题思路
方法一:计数
我们观察题目中的操作,可以发现,如果字符串的两个下标 和 的奇偶性相同,那么它们可以通过交换改变顺序。
因此,我们可以统计两个字符串中奇数下标的字符的出现次数,以及偶数下标的字符的出现次数,如果两个字符串的统计结果相同,那么我们就可以通过操作使得两个字符串相等。
时间复杂度 ,空间复杂度 。其中 是字符串的长度,而 是字符集。
相似题目:
class Solution:
def checkStrings(self, s1: str, s2: str) -> bool:
return Counter(s1[::2]) == Counter(s2[::2]) and Counter(s1[1::2]) == Counter(
s2[1::2]
)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Assess whether the candidate can think through the problem with the correct pattern, focusing on parity and hashing.
- question_mark
Look for an understanding of string manipulation and character frequency counting for efficient solutions.
- question_mark
Evaluate how the candidate handles edge cases, such as strings with mismatched characters or impossible swaps.
常见陷阱
外企场景- error
Forgetting to account for the parity constraint in swaps, leading to incorrect conclusions about the possibility of equalizing the strings.
- error
Overcomplicating the problem with unnecessary operations instead of focusing on character parity and frequency.
- error
Not considering edge cases like when the strings are already equal or contain only one character.
进阶变体
外企场景- arrow_right_alt
Introduce a condition where swaps are allowed only between characters at specific intervals or positions, testing how well the candidate adapts the solution.
- arrow_right_alt
Modify the problem to handle strings of varying lengths, where padding or trimming may be necessary before applying the operations.
- arrow_right_alt
Increase the complexity by introducing constraints on the number of swaps allowed, adding a new layer of problem-solving.