LeetCode 题解工作台

使字符串中不同字符的数目相等

给你两个下标从 0 开始的字符串 word1 和 word2 。 一次 移动 由以下两个步骤组成: 选中两个下标 i 和 j ,分别满足 0 和 0 , 交换 word1[i] 和 word2[j] 。 如果可以通过 恰好一次 移动,使 word1 和 word2 中不同字符的数目相等,则返回 tr…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 哈希·表·结合·string

bolt

答案摘要

我们先用两个长度为 的数组 和 分别记录字符串 和 中每个字符的出现次数。 然后我们分别统计 和 中不同字符的个数,分别记为 和 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个下标从 0 开始的字符串 word1word2

一次 移动 由以下两个步骤组成:

  • 选中两个下标 ij ,分别满足 0 <= i < word1.length0 <= j < word2.length
  • 交换 word1[i]word2[j]

如果可以通过 恰好一次 移动,使 word1word2 中不同字符的数目相等,则返回 true ;否则,返回 false

 

示例 1:

输入:word1 = "ac", word2 = "b"
输出:false
解释:交换任何一组下标都会导致第一个字符串中有 2 个不同的字符,而在第二个字符串中只有 1 个不同字符。

示例 2:

输入:word1 = "abcc", word2 = "aab"
输出:true
解释:交换第一个字符串的下标 2 和第二个字符串的下标 0 。之后得到 word1 = "abac" 和 word2 = "cab" ,各有 3 个不同字符。

示例 3:

输入:word1 = "abcde", word2 = "fghij"
输出:true
解释:无论交换哪一组下标,两个字符串中都会有 5 个不同字符。

 

提示:

  • 1 <= word1.length, word2.length <= 105
  • word1word2 仅由小写英文字母组成。
lightbulb

解题思路

方法一:计数 + 枚举

我们先用两个长度为 2626 的数组 cnt1\textit{cnt1}cnt2\textit{cnt2} 分别记录字符串 word1\textit{word1}word2\textit{word2} 中每个字符的出现次数。

然后我们分别统计 word1\textit{word1}word2\textit{word2} 中不同字符的个数,分别记为 xxyy

接下来我们枚举 word1\textit{word1} 中的每个字符 c1c1word2\textit{word2} 中的每个字符 c2c2,如果 c1=c2c1 = c2,那么我们只需要判断 xxyy 是否相等;否则,我们需要判断 x(cnt1[c1]=1)+(cnt1[c2]=0)x - (\textit{cnt1}[c1] = 1) + (\textit{cnt1}[c2] = 0)y(cnt2[c2]=1)+(cnt2[c1]=0)y - (\textit{cnt2}[c2] = 1) + (\textit{cnt2}[c1] = 0) 是否相等。如果相等,那么我们就找到了一种方案,返回 true\text{true}

如果我们枚举完所有的字符都没有找到合适的方案,那么我们就返回 false\text{false}

时间复杂度 O(m+n+Σ2)O(m + n + |\Sigma|^2),其中 mmnn 分别是字符串 word1\textit{word1}word2\textit{word2} 的长度,而 Σ\Sigma 是字符集,本题中字符集为小写字母,所以 Σ=26|\Sigma| = 26

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
    def isItPossible(self, word1: str, word2: str) -> bool:
        cnt1 = Counter(word1)
        cnt2 = Counter(word2)
        x, y = len(cnt1), len(cnt2)
        for c1, v1 in cnt1.items():
            for c2, v2 in cnt2.items():
                if c1 == c2:
                    if x == y:
                        return True
                else:
                    a = x - (v1 == 1) + (cnt1[c2] == 0)
                    b = y - (v2 == 1) + (cnt2[c1] == 0)
                    if a == b:
                        return True
        return False
speed

复杂度分析

指标
时间complexity depends on the number of unique characters in each string, typically O(26*26) due to limited lowercase letters, and space complexity is O(26) per string for frequency maps.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Pay attention to edge cases where one string has only duplicates.

  • question_mark

    Watch for off-by-one errors when counting distinct characters after a swap.

  • question_mark

    Consider how swapping identical characters affects distinct counts.

warning

常见陷阱

外企场景
  • error

    Assuming any swap will work without checking distinct counts.

  • error

    Failing to handle swaps involving characters already present in both strings.

  • error

    Overlooking the need to update counts after each simulated swap.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Allow multiple swaps to equalize distinct characters instead of exactly one.

  • arrow_right_alt

    Limit swaps to adjacent characters only and evaluate feasibility.

  • arrow_right_alt

    Consider uppercase and lowercase letters, increasing the character set size.

help

常见问题

外企场景

使字符串中不同字符的数目相等题解:哈希·表·结合·string | LeetCode #2531 中等