LeetCode 题解工作台
有效的字母异位词
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的 字母异位词 。 示例 1: 输入: s = "anagram", t = "nagaram" 输出: true 示例 2: 输入: s = "rat", t = "car" 输出: false 提示: 1 4 s 和 t 仅包含小…
3
题型
9
代码语言
3
相关题
当前训练重点
简单 · 哈希·表·结合·string
答案摘要
我们先判断两个字符串的长度是否相等,如果不相等,说明两个字符串中的字符肯定不同,返回 `false`。 否则,我们用哈希表或者一个长度为 的数组来记录字符串 中每个字符出现的次数,然后遍历另一个字符串 ,每遍历到一个字符,就将哈希表中对应的字符次数减一,如果减一后的次数小于 ,说明该字符在两个字符串中出现的次数不同,返回 `false`。如果遍历完两个字符串后,哈希表中的所有字符次数都为 ,说…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的 字母异位词。
示例 1:
输入: s = "anagram", t = "nagaram" 输出: true
示例 2:
输入: s = "rat", t = "car" 输出: false
提示:
1 <= s.length, t.length <= 5 * 104s和t仅包含小写字母
进阶: 如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
解题思路
方法一:计数
我们先判断两个字符串的长度是否相等,如果不相等,说明两个字符串中的字符肯定不同,返回 false。
否则,我们用哈希表或者一个长度为 的数组来记录字符串 中每个字符出现的次数,然后遍历另一个字符串 ,每遍历到一个字符,就将哈希表中对应的字符次数减一,如果减一后的次数小于 ,说明该字符在两个字符串中出现的次数不同,返回 false。如果遍历完两个字符串后,哈希表中的所有字符次数都为 ,说明两个字符串中的字符出现次数相同,返回 true。
时间复杂度 ,空间复杂度 ,其中 是字符串的长度;而 是字符集的大小,本题中 。
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
cnt = Counter(s)
for c in t:
cnt[c] -= 1
if cnt[c] < 0:
return False
return True
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Looking for efficient solutions using hashing or sorting.
- question_mark
Expect optimization in terms of space or time based on input constraints.
- question_mark
Can test with edge cases like large inputs to evaluate performance.
常见陷阱
外企场景- error
Using a hash table can lead to excessive space usage for large inputs.
- error
Sorting may cause performance issues with strings near the upper length limit.
- error
Overcomplicating the solution with unnecessary operations or data structures.
进阶变体
外企场景- arrow_right_alt
Use an extended character set, e.g., Unicode, to test solution robustness.
- arrow_right_alt
Change the problem to ignore case or spaces.
- arrow_right_alt
Implement case-sensitive anagram checks.