LeetCode 题解工作台

仅执行一次字符串交换能否使两个字符串相等

给你长度相等的两个字符串 s1 和 s2 。一次 字符串交换 操作的步骤如下:选出某个字符串中的两个下标(不必不同),并交换这两个下标所对应的字符。 如果对 其中一个字符串 执行 最多一次字符串交换 就可以使两个字符串相等,返回 true ;否则,返回 false 。 示例 1: 输入: s1 = …

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 哈希·表·结合·string

bolt

答案摘要

我们用变量 记录两个字符串中相同位置字符不同的个数,两个字符串若满足题目要求,那么 一定为 或 。另外用两个字符变量 和 记录两个字符串中相同位置字符不同的字符。 同时遍历两个字符串,对于相同位置的两个字符 和 ,如果 $a \ne b$,那么 自增 。如果此时 大于 ,或者 为 且 $a \ne c2$ 或 $b \ne c1$,那么直接返回 `false`。注意记录一下 …

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你长度相等的两个字符串 s1s2 。一次 字符串交换 操作的步骤如下:选出某个字符串中的两个下标(不必不同),并交换这两个下标所对应的字符。

如果对 其中一个字符串 执行 最多一次字符串交换 就可以使两个字符串相等,返回 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 <= 100
  • s1.length == s2.length
  • s1s2 仅由小写英文字母组成
lightbulb

解题思路

方法一:计数

我们用变量 cntcnt 记录两个字符串中相同位置字符不同的个数,两个字符串若满足题目要求,那么 cntcnt 一定为 0022。另外用两个字符变量 c1c1c2c2 记录两个字符串中相同位置字符不同的字符。

同时遍历两个字符串,对于相同位置的两个字符 aabb,如果 aba \ne b,那么 cntcnt 自增 11。如果此时 cntcnt 大于 22,或者 cntcnt22ac2a \ne c2bc1b \ne c1,那么直接返回 false。注意记录一下 c1c1c2c2

遍历结束,若 cnt1cnt \neq 1,返回 true

时间复杂度 O(n)O(n),其中 nn 为字符串长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
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
speed

复杂度分析

指标
时间O(N)
空间O(1)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

仅执行一次字符串交换能否使两个字符串相等题解:哈希·表·结合·string | LeetCode #1790 简单