LeetCode 题解工作台
仅执行一次字符串交换能否使两个字符串相等
给你长度相等的两个字符串 s1 和 s2 。一次 字符串交换 操作的步骤如下:选出某个字符串中的两个下标(不必不同),并交换这两个下标所对应的字符。 如果对 其中一个字符串 执行 最多一次字符串交换 就可以使两个字符串相等,返回 true ;否则,返回 false 。 示例 1: 输入: s1 = …
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 哈希·表·结合·string
答案摘要
我们用变量 记录两个字符串中相同位置字符不同的个数,两个字符串若满足题目要求,那么 一定为 或 。另外用两个字符变量 和 记录两个字符串中相同位置字符不同的字符。 同时遍历两个字符串,对于相同位置的两个字符 和 ,如果 $a \ne b$,那么 自增 。如果此时 大于 ,或者 为 且 $a \ne c2$ 或 $b \ne c1$,那么直接返回 `false`。注意记录一下 …
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
给你长度相等的两个字符串 s1 和 s2 。一次 字符串交换 操作的步骤如下:选出某个字符串中的两个下标(不必不同),并交换这两个下标所对应的字符。
如果对 其中一个字符串 执行 最多一次字符串交换 就可以使两个字符串相等,返回 true ;否则,返回 false 。
示例 1:
输入:s1 = "bank", s2 = "kanb" 输出:true 解释:例如,交换 s2 中的第一个和最后一个字符可以得到 "bank"
示例 2:
输入:s1 = "attack", s2 = "defend" 输出:false 解释:一次字符串交换无法使两个字符串相等
示例 3:
输入:s1 = "kelb", s2 = "kelb" 输出:true 解释:两个字符串已经相等,所以不需要进行字符串交换
示例 4:
输入:s1 = "abcd", s2 = "dcba" 输出:false
提示:
1 <= s1.length, s2.length <= 100s1.length == s2.lengths1和s2仅由小写英文字母组成
解题思路
方法一:计数
我们用变量 记录两个字符串中相同位置字符不同的个数,两个字符串若满足题目要求,那么 一定为 或 。另外用两个字符变量 和 记录两个字符串中相同位置字符不同的字符。
同时遍历两个字符串,对于相同位置的两个字符 和 ,如果 ,那么 自增 。如果此时 大于 ,或者 为 且 或 ,那么直接返回 false。注意记录一下 和 。
遍历结束,若 ,返回 true。
时间复杂度 ,其中 为字符串长度。空间复杂度 。
class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
cnt = 0
c1 = c2 = None
for a, b in zip(s1, s2):
if a != b:
cnt += 1
if cnt > 2 or (cnt == 2 and (a != c2 or b != c1)):
return False
c1, c2 = a, b
return cnt != 1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(N) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
The candidate should efficiently identify mismatched character positions.
- question_mark
The candidate should recognize the importance of string length and how to handle identical strings directly.
- question_mark
The candidate should avoid unnecessary operations, focusing on counting mismatches and validating potential swaps.
常见陷阱
外企场景- error
Confusing the number of mismatches, which must be 0 or 2 for a valid swap.
- error
Not checking if swapping characters at mismatched positions results in the strings becoming equal.
- error
Failing to handle the case where the strings are already equal.
进阶变体
外企场景- arrow_right_alt
Handling cases with different character sets, not just lowercase letters.
- arrow_right_alt
Considering cases with larger strings where performance may be more important.
- arrow_right_alt
Handling strings with more complex structures or patterns beyond simple swaps.