mirror of
https://github.com/Rainyy21/framework_note.git
synced 2026-10-11 00:20:29 -04:00
3.0 KiB
3.0 KiB
id, title, difficulty, tags, status, date_solved, leetcode_url, review_needed
| id | title | difficulty | tags | status | date_solved | leetcode_url | review_needed | ||
|---|---|---|---|---|---|---|---|---|---|
| 290 | Word Pattern | Easy |
|
Solved | 2026-06-05 | https://leetcode.com/problems/word-pattern/ | false |
290. Word Pattern
[!info] Problem Link: LeetCode - Word Pattern
📝 Problem Description
Given a pattern and a string s, find if s follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.
📥 Example 1
Input:
pattern = "abba",s = "dog cat cat dog"Output:true
📥 Example 2
Input:
pattern = "abba",s = "dog cat cat fish"Output:false
📥 Example 3
Input:
pattern = "aaaa",s = "dog cat cat dog"Output:false
💡 Approaches & Explanations
Approach 1: Two Hash Maps (Bijective Mapping) — Optimal
To ensure a bijection (one-to-one mapping) between characters in pattern and words in s, we need to verify two things:
- Every character in
patternmaps to exactly one word ins. - Every word in
smaps to exactly one character inpattern.
Using two hash maps allows us to track these mappings in both directions. Alternatively, we can use one hash map for the mapping and a set to ensure the values are unique.
📊 Complexity Analysis
- Time Complexity:
\mathcal{O}(N + M)whereNis the number of characters in the pattern andMis the number of characters in strings. We split the string and then iterate through the pattern. - Space Complexity:
\mathcal{O}(W)whereWis the number of unique words insand unique characters inpattern.
💻 Code Implementations
Python3
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split()
if len(pattern) != len(words):
return False
char_to_word = {}
word_to_char = {}
for char, word in zip(pattern, words):
if char in char_to_word:
if char_to_word[char] != word:
return False
else:
char_to_word[char] = word
if word in word_to_char:
if word_to_char[word] != char:
return False
else:
word_to_char[word] = char
return True
🧠 Key Takeaways & Lessons
- Bijective Mapping: When a problem requires a 1-to-1 relationship, remember that a single hash map only tracks the mapping in one direction. You must either use two maps or check that the values in the single map are unique.
- String Splitting: Python's
.split()defaults to splitting by any whitespace, which is perfect for space-separated word problems. - Zip for Parallel Iteration: The
zip()function is an idiomatic way to iterate over two sequences simultaneously.