LeetCode 题解工作台
检查两个字符串是否几乎相等
如果两个字符串 word1 和 word2 中从 'a' 到 'z' 每一个字母出现频率之差都 不超过 3 ,那么我们称这两个字符串 word1 和 word2 几乎相等 。 给你两个长度都为 n 的字符串 word1 和 word2 ,如果 word1 和 word2 几乎相等 ,请你返回 tru…
3
题型
8
代码语言
3
相关题
当前训练重点
简单 · 哈希·表·结合·string
答案摘要
我们可以创建一个长度为 的数组 ,记录两个字符串中每个字母出现的次数之差。最后遍历 ,如果有任意一个字母出现的次数之差大于 ,则返回 `false`,否则返回 `true`。 时间复杂度 ,空间复杂度 。其中 是字符串的长度;而 是字符集的大小,本题中 $C = 26$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
如果两个字符串 word1 和 word2 中从 'a' 到 'z' 每一个字母出现频率之差都 不超过 3 ,那么我们称这两个字符串 word1 和 word2 几乎相等 。
给你两个长度都为 n 的字符串 word1 和 word2 ,如果 word1 和 word2 几乎相等 ,请你返回 true ,否则返回 false 。
一个字母 x 的出现 频率 指的是它在字符串中出现的次数。
示例 1:
输入:word1 = "aaaa", word2 = "bccb" 输出:false 解释:字符串 "aaaa" 中有 4 个 'a' ,但是 "bccb" 中有 0 个 'a' 。 两者之差为 4 ,大于上限 3 。
示例 2:
输入:word1 = "abcdeef", word2 = "abaaacc" 输出:true 解释:word1 和 word2 中每个字母出现频率之差至多为 3 : - 'a' 在 word1 中出现了 1 次,在 word2 中出现了 4 次,差为 3 。 - 'b' 在 word1 中出现了 1 次,在 word2 中出现了 1 次,差为 0 。 - 'c' 在 word1 中出现了 1 次,在 word2 中出现了 2 次,差为 1 。 - 'd' 在 word1 中出现了 1 次,在 word2 中出现了 0 次,差为 1 。 - 'e' 在 word1 中出现了 2 次,在 word2 中出现了 0 次,差为 2 。 - 'f' 在 word1 中出现了 1 次,在 word2 中出现了 0 次,差为 1 。
示例 3:
输入:word1 = "cccddabba", word2 = "babababab" 输出:true 解释:word1 和 word2 中每个字母出现频率之差至多为 3 : - 'a' 在 word1 中出现了 2 次,在 word2 中出现了 4 次,差为 2 。 - 'b' 在 word1 中出现了 2 次,在 word2 中出现了 5 次,差为 3 。 - 'c' 在 word1 中出现了 3 次,在 word2 中出现了 0 次,差为 3 。 - 'd' 在 word1 中出现了 2 次,在 word2 中出现了 0 次,差为 2 。
提示:
n == word1.length == word2.length1 <= n <= 100word1和word2都只包含小写英文字母。
解题思路
方法一:计数
我们可以创建一个长度为 的数组 ,记录两个字符串中每个字母出现的次数之差。最后遍历 ,如果有任意一个字母出现的次数之差大于 ,则返回 false,否则返回 true。
时间复杂度 ,空间复杂度 。其中 是字符串的长度;而 是字符集的大小,本题中 。
class Solution:
def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:
cnt = Counter(word1)
for c in word2:
cnt[c] -= 1
return all(abs(x) <= 3 for x in cnt.values())
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(N) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
They want counting, not sorting, because only per-letter frequency differences matter.
- question_mark
The fixed alphabet size hints that an array of 26 is cleaner than a general map.
- question_mark
An early return on any difference greater than 3 shows you understand the exact acceptance condition.
常见陷阱
外企场景- error
Comparing total mismatches instead of checking each individual letter gap against 3.
- error
Using sorting, which adds unnecessary work and hides the direct counting pattern of this problem.
- error
Forgetting letters that appear in one word but not the other, which is exactly why "aaaa" versus "bccb" fails.
进阶变体
外企场景- arrow_right_alt
Change the threshold from 3 to k and keep the same counting scan.
- arrow_right_alt
Allow uppercase or arbitrary characters, which shifts the 26-slot array toward a hash map.
- arrow_right_alt
Ask for the maximum frequency gap instead of a boolean result, using the same counts but a different final check.