LeetCode 题解工作台
单词规律
给定一种规律 pattern 和一个字符串 s ,判断 s 是否遵循相同的规律。 这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。具体来说: pattern 中的每个字母都 恰好 映射到 s 中的一个唯一单词。 s 中的每个唯…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 哈希·表·结合·string
答案摘要
我们先将字符串 按照空格分割成单词数组 ,如果 和 的长度不相等,直接返回 `false`。否则,我们使用两个哈希表 和 ,分别记录 和 中每个字符和单词的对应关系。 接下来,我们遍历 和 ,对于每个字符 和单词 ,如果 中存在 的映射,且映射的单词不是 ,或者 中存在 的映射,且映射的字符不是 ,则返回 `false`。否则,我们将 和 的映射分别加入 和 中。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
给定一种规律 pattern 和一个字符串 s ,判断 s 是否遵循相同的规律。
这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。具体来说:
pattern中的每个字母都 恰好 映射到s中的一个唯一单词。s中的每个唯一单词都 恰好 映射到pattern中的一个字母。- 没有两个字母映射到同一个单词,也没有两个单词映射到同一个字母。
示例1:
输入: pattern ="abba", s ="dog cat cat dog"输出: true
示例 2:
输入:pattern ="abba", s ="dog cat cat fish"输出: false
示例 3:
输入: pattern ="aaaa", s ="dog cat cat dog"输出: false
提示:
1 <= pattern.length <= 300pattern只包含小写英文字母1 <= s.length <= 3000s只包含小写英文字母和' 's不包含 任何前导或尾随对空格s中每个单词都被 单个空格 分隔
解题思路
方法一:哈希表
我们先将字符串 按照空格分割成单词数组 ,如果 和 的长度不相等,直接返回 false。否则,我们使用两个哈希表 和 ,分别记录 和 中每个字符和单词的对应关系。
接下来,我们遍历 和 ,对于每个字符 和单词 ,如果 中存在 的映射,且映射的单词不是 ,或者 中存在 的映射,且映射的字符不是 ,则返回 false。否则,我们将 和 的映射分别加入 和 中。
遍历结束后,返回 true。
时间复杂度 ,空间复杂度 。其中 和 分别是 和字符串 的长度。
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
ws = s.split()
if len(pattern) != len(ws):
return False
d1 = {}
d2 = {}
for a, b in zip(pattern, ws):
if (a in d1 and d1[a] != b) or (b in d2 and d2[b] != a):
return False
d1[a] = b
d2[b] = a
return True
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
They want you to say "bijection" or explicitly explain why checking only character-to-word mapping is insufficient.
- question_mark
They expect an early length check after splitting, because Word Pattern requires every pattern position to match one word.
- question_mark
They may probe whether two different letters can map to the same word, which reveals whether you handled the reverse mapping.
常见陷阱
外企场景- error
Using only one hash map and accidentally accepting cases where two pattern letters share one word.
- error
Forgetting to compare word count against pattern length before building mappings.
- error
Treating this like substring matching instead of exact token-by-token word matching separated by spaces.
进阶变体
外企场景- arrow_right_alt
Return the actual mapping for Word Pattern instead of only true or false.
- arrow_right_alt
Handle an input where words are streamed one by one instead of pre-splitting the full string.
- arrow_right_alt
Generalize the same bijection check to pattern tokens and sentence tokens beyond single characters and lowercase words.