Design Add and Search Words Data Structure
הקוד שלכם עדיין לא נשמר: רענון או יציאה מהדף מאפסים אותו. שמירת התקדמות תגיע יחד עם חשבונות משתמשים.
תכננו מילון מילים שתומך בחיפוש עם wildcards (תווים כלליים).
ממשו את המחלקה WordDictionary:
new WordDictionary()יוצרת מילון ריק.addWord(word)מוסיפה אתword.search(word)מחזירהtrueאם מילה כלשהי שהוספה תואמת ל-word.
הבנת הבעיה
- wildcard הוא תו שמייצג "כל דבר". כאן זו הנקודה
., והיא מתאימה לאות אחת בדיוק, כל אות. - מילה תואמת למחרוזת החיפוש אם יש להן אותו אורך וכל אות שאינה נקודה שווה באותו מיקום.
".ad"תואם ל-"bad","dad"ו-"mad"."b.."תואם לכל מילה בת 3 אותיות שמתחילה ב-b. אבל".ad"לא תואם ל-"ad"או ל-"bead": האורכים חייבים להיות שווים.
דוגמה 1
ops: ["WordDictionary", "addWord", "addWord", "addWord", "search", "search", "search", "search"]
args: [[], ["bad"], ["dad"], ["mad"], ["pad"], ["bad"], [".ad"], ["b.."]]
expected: [null, null, null, null, false, true, true, true]search("pad")←false: לא הוספה אף פעם.search("bad")←true: הוספה.search(".ad")←true:"bad"תואמת (וגם"dad"ו-"mad").search("b..")←true:"bad"תואמת.
איך הטסטים עובדים: כל טסט הוא רצף של קריאות. ops נותן שם לכל קריאה (הראשונה יוצרת את האובייקט), args מחזיק את הארגומנטים, ו-expected את ערכי ההחזרה.
אילוצים
1 <= word.length <= 25- מילים שמוסיפים מכילות אותיות אנגליות קטנות; מחרוזות חיפוש יכולות להכיל גם
.. - במחרוזת חיפוש יש לכל היותר 2 נקודות.
- לכל היותר
10^4קריאות בסך הכל.
רמזים
נתקעתם? פתחו רמז אחד בכל פעם. כל רמז מגלה קצת יותר מהקודם.
הרעיון במשפט אחד
שומרים את המילים ב-trie; החיפוש הולך בו אות אחרי אות, ובנקודה מנסה כל ילד ומצליח אם אחד מהם מוביל להתאמה.
הגישה הנאיבית (ולמה היא איטית)
שומרים את המילים ברשימה. בכל חיפוש, משווים לכל מילה: אותו אורך, וכל אות שאינה נקודה שווה. זה O(מספר מילים × אורך) לכל חיפוש: עם 10,000 מילים והרבה חיפושים, זה מצטבר.
התובנה המרכזית
משתמשים ב-trie מ-Implement Trie. addWord זהה ל-insert, וחיפוש בלי נקודות הוא אותה הליכה כמו search.
הדבר החדש היחיד הוא הנקודה. באות רגילה, יש בדיוק ילד אחד ללכת אליו. ב-., האות יכולה להיות כל דבר, אז החיפוש מתפצל: מנסים כל ילד, ואם ענף כלשהו תואם, התשובה היא true.
match(node, i): "can word[i..] be found below node?"
i == word.length → node.isEnd (used every character: did a word end here?)
word[i] == '.' → true if ANY child c has match(c, i + 1)
otherwise → follow the child for word[i]; false if it doesn't existזה depth-first search (DFS) שמתפשט רק בנקודות. כל אות אמיתית הולכת במסלול יחיד, אז רוב ה-trie אף פעם לא נסרק.
צעד אחר צעד
אחרי הוספת bad, dad, mad, ל-root של ה-trie יש שלושה ילדים: b, d, m, וכל אחד ממשיך עם a ואז d (סוף).
חיפוש ".ad":
| מיקום | תו | ב-node | מה קורה |
|---|---|---|---|
| 0 | . | root | מנסים כל ילד: קודם b |
| 1 | a | b | הולכים ל-a |
| 2 | d | b → a | הולכים ל-d |
| 3 | (סוף) | b → a → d | isEnd הוא true ← התאמה! |
הענף הראשון כבר התאים, אז מחזירים true בלי לנסות את d או m.
הקוד
הפתרון לדוגמה מופיע למטה, עם הערות על כל שורה חשובה.
כמה זה מהיר?
כש-L = אורך המילה ו-d = מספר הנקודות:
addWord: O(L).search: O(L) בלי נקודות. כל נקודה יכולה להתפצל לעד 26 ילדים, אז המקרה הגרוע הוא בערך O(26^d · L). עם לכל היותר 2 נקודות, זה עדיין קטן.- זיכרון: O(סך כל האותיות שהוספו).
טעויות נפוצות
- להחזיר
trueכשהמסלול קיים אבל אף מילה לא נגמרת שם. בסוף, בודקיםisEnd. - להחזיר את התוצאה של הילד הראשון בנקודה. אם הילד הראשון נכשל, צריך לנסות את האחרים. מחזירים
falseרק אחרי שכל הילדים נכשלו. - לתת לנקודה להתאים ל"אפס אותיות" או לכמה אותיות. היא מתאימה לאחת בדיוק.
להעמקה
זה כוח העל האמיתי של trie: חיפוש שמונחה על ידי תחילית שגוזם כל מה שלא תואם עד עכשיו. אותו רעיון, DFS שזז ב-trie ובמבנה נוסף באותו זמן, הוא הלב של Word Search II.
פתרון לדוגמה
class TrieNode {
children = new Map() // letter → next node
isEnd = false // does a whole word end at this node?
}
export default class WordDictionary {
root = new TrieNode()
/**
* @param {string} word
* @return {void}
*/
// Exactly Trie.insert: follow the letters, creating nodes as needed, then mark the end.
addWord(word) {
let node = this.root
for (const char of word) {
if (!node.children.has(char)) node.children.set(char, new TrieNode())
node = node.children.get(char)
}
node.isEnd = true
}
/**
* @param {string} word
* @return {boolean}
*/
search(word) {
// Can word[i..] be found starting below this node?
const match = (node, i) => {
// Used every character: it's a match only if a word ends right here.
if (i === word.length) return node.isEnd
if (word[i] === '.') {
// A dot can be ANY letter: try every child, succeed if any branch matches.
for (const child of node.children.values()) {
if (match(child, i + 1)) return true
}
return false
}
// A normal letter: there's only one way to go.
const child = node.children.get(word[i])
return child !== undefined && match(child, i + 1)
}
return match(this.root, 0)
}
}class TrieNode {
children = new Map<string, TrieNode>() // letter → next node
isEnd = false // does a whole word end at this node?
}
export default class WordDictionary {
private root = new TrieNode()
// Exactly Trie.insert: follow the letters, creating nodes as needed, then mark the end.
addWord(word: string): void {
let node = this.root
for (const char of word) {
let child = node.children.get(char)
if (!child) {
child = new TrieNode()
node.children.set(char, child)
}
node = child
}
node.isEnd = true
}
search(word: string): boolean {
// Can word[i..] be found starting below this node?
const match = (node: TrieNode, i: number): boolean => {
// Used every character: it's a match only if a word ends right here.
if (i === word.length) return node.isEnd
if (word[i] === '.') {
// A dot can be ANY letter: try every child, succeed if any branch matches.
for (const child of node.children.values()) {
if (match(child, i + 1)) return true
}
return false
}
// A normal letter: there's only one way to go.
const child = node.children.get(word[i])
return child !== undefined && match(child, i + 1)
}
return match(this.root, 0)
}
}class TrieNode:
def __init__(self):
self.children: dict[str, TrieNode] = {} # letter → next node
self.is_end = False # does a whole word end at this node?
class WordDictionary:
def __init__(self):
self.root = TrieNode()
# Exactly Trie.insert: follow the letters, creating nodes as needed, then mark the end.
def add_word(self, word: str) -> None:
node = self.root
for char in word:
node = node.children.setdefault(char, TrieNode())
node.is_end = True
def search(self, word: str) -> bool:
# Can word[i:] be found starting below this node?
def match(node: TrieNode, i: int) -> bool:
# Used every character: it's a match only if a word ends right here.
if i == len(word):
return node.is_end
if word[i] == ".":
# A dot can be ANY letter: try every child, succeed if any branch matches.
return any(match(child, i + 1) for child in node.children.values())
# A normal letter: there's only one way to go.
child = node.children.get(word[i])
return child is not None and match(child, i + 1)
return match(self.root, 0)