Python算法训练序列
数组与哈希 · Unit 03
← Unit 02
242
LeetCode 242Valid Anagram · 有效的字母异位词
相同字符出现相同次数,
顺序就不再重要。
前两个单元分别保存“是否出现”和“出现位置”。这一单元继续升级哈希状态:为每个字符保存出现次数,使两个不同顺序的字符串可以被压缩为同一份字符库存。
LeetCode #242 原题内容
中文转述 · 保留示例、约束与进阶问题
题目要求
给定两个字符串 s 和 t。如果 t 是 s 的字母异位词,返回 True,否则返回 False。字母异位词使用完全相同的字符及出现次数,但字符顺序可以不同。
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# 在这里提交答案
约束
1 ≤ len(s), len(t) ≤ 50000s和t只包含小写英文字母。- 进阶:如果输入包含 Unicode 字符,怎样调整方案?
示例
s = "anagram"
t = "nagaram"
输出:True
t = "nagaram"
输出:True
s = "rat"
t = "car"
输出:False
t = "car"
输出:False
1. 忽略顺序
2. 建立字符库存
3. 正负计数抵消
4. 代码联动
5. Unicode迁移
s
t
字符库存 count字符 → 净出现次数
count = {}
当前阶段—
当前索引 i—
当前字符—
本次变化—
最终判断—
补全 LeetCode 提交代码卡住可查看参考答案
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if :
return False
count =
for ch in s:
count[ch] =
for ch in t:
if :
return False
return True
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
count = {}
for ch in s:
count[ch] = count.get(ch, 0) + 1
for ch in t:
if count.get(ch, 0) == 0:
return False
count[ch] -= 1
return True
为什么不直接使用集合?因为
"aab" 与 "abb" 的字符集合都是 {a,b},但频次不同。也可以使用 Counter(s) == Counter(t) 或排序比较;本单元保留显式计数过程,以便动画展示库存如何增加和抵消。代码—字符串—计数字典联动示例:s="abb",t="bab"
1class Solution:
2 def isAnagram(self, s: str, t: str) -> bool:
3 if len(s) != len(t):
4 return False
5 count = {}
6 for ch in s:
7 count[ch] = count.get(ch, 0) + 1
8 for ch in t:
9 if count.get(ch, 0) == 0:
10 return False
11 count[ch] -= 1
12 return True
逐行播放,观察 s 增加库存、t 消耗库存。
完成代码联动后进入 Unicode 迁移
补全正确、查看答案或播放完整轨迹后解锁。
迁移题:输入包含 Unicode 字符怎么办?
例如 s="你好好"、t="好你好"。固定长度为26的数组只适合小写英文字母;Python 字典和 collections.Counter 可以直接使用 Unicode 字符作为键。请写出一个简洁版本。
本单元形成的算法Skill
当对象的顺序不重要、但组成必须完全一致时,用频次映射构造“库存向量”。扫描第一组对象时增加库存,扫描第二组对象时消耗库存;任何库存不足都意味着组成不同。
LeetCode #242频次字典先长度剪枝增加/抵消时间 O(n)空间 O(k)
#217 哈希集合是否出现过
#1 哈希映射出现在哪里
#242 当前:频次统计出现多少次
#49 下一单元:分组键把频次向量作为身份