NeetCode #57LC-290EasyArrays & Hashing
← Back to All Problems#57 · #290 · Word Pattern(单词规律)
📌 Problem Statement & Constraints
Given a
pattern string and a string s, determine whether s follows the same pattern: each letter of pattern must map bijectively to a whitespace-separated word of s. Constraints: 1 <= pattern.length <= 300, 1 <= s.length <= 3000; pattern contains only lowercase letters; s contains lowercase letters and spaces.💡 Core Algorithmic Approaches
- Split
sinto words and compare the counts withpatternfirst. - Then build a bijection in both directions, exactly as in Isomorphic Strings.
- The forward map ensures one letter always maps to the same word; the reverse map ensures two different letters cannot map to the same word.
- Both directions are required:
pattern = "ab",s = "dog dog"must fail.
💻 Benchmark Python3 Implementation
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split()
if len(pattern) != len(words):
return False
fwd = {} # letter -> word
rev = {} # word -> letter
for ch, w in zip(pattern, words):
if fwd.get(ch, w) != w or rev.get(w, ch) != ch:
return False # bijection violated
fwd[ch] = w
rev[w] = ch
return True⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n + total characters): splitting is linear in s, and the pairing loop is linear in the number of words.
💾 Space Complexity
O(k) for the two maps and the word list.
⚠️ Interview Pitfalls & Follow-ups
- Using only one map:
pattern = "ab",s = "dog dog"would be wrongly accepted. - Forgetting the length check: unequal counts must fail, and
zipwould silently truncate. - Splitting on
' 'explicitly:s.split(' ')creates empty strings for repeated spaces;s.split()collapses runs of whitespace and is safer. - Comparing character frequencies instead of building a bijection: frequency equality is necessary but not sufficient.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
单词规律
给定一种规律 pattern 和一个字符串 s,判断 s 是否遵循相同的规律。这里的「遵循」指完全匹配,例如 pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着 双向连接 的对应规律。约束:1 ≤ pattern.length ≤ 300;pattern 仅含小写英文字母;1 ≤ s.length ≤ 3000;s 仅含小写英文字母和空格;s 不含前导或尾随空格。
核心要点
- 双向映射(标准解) :把 s 按空格切分成单词列表,先检查长度是否与 pattern 相同,再维护两个字典—— pattern → word 与 word → pattern 。
- 为什么必须双向 :只建单向会漏掉「多个 pattern 字符映射到同一个单词」的情况(如 pattern = "ab"、s = "dog dog")。
- 实现细节 :用 dict.setdefault(key, val) 一行完成「不存在则写入、存在则返回已有值」的一致性检查。
- 等价方案 :分别把 pattern 与单词列表归一化为「首次出现顺序的编号序列」,比较两个序列。
常见陷阱
- 只建单向映射 :pattern = "ab"、s = "dog dog" 在单向映射下会被误判为遵循规律,实际不遵循(两个不同字母映射到同一单词)。
- 忘记长度检查 :pattern 长度与单词数不等时必然不遵循,应先剪枝。
- 用 split(" ") 切分 :题目保证 s 不含前导/尾随空格且单词间为单个空格,因此两种切分等价;但用无参数的 split() 更稳健。
- 与 205 同构字符串混淆写法 :205 是字符对字符,本题是字符对单词,框架相同但键值类型不同。
参考实现
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split()
if len(pattern) != len(words):
return False
p2w, w2p = {}, {}
for p, w in zip(pattern, words):
if p2w.setdefault(p, w) != w: # pattern -> word 必须一致
return False
if w2p.setdefault(w, p) != p: # word -> pattern 必须一致(双向)
return False
return True