Word Break
הקוד שלכם עדיין לא נשמר: רענון או יציאה מהדף מאפסים אותו. שמירת התקדמות תגיע יחד עם חשבונות משתמשים.
בהינתן מחרוזת s ורשימת מילים wordDict, החזירו true אם אפשר לפצל את s לרצף של מילה אחת או יותר מהמילון, בלי שישאר כלום. כל מילה יכולה לשמש כמה פעמים שרוצים.
הבנת הבעיה
- חותכים את
sלחתיכות, וכל חתיכה חייבת להיות מילה מ-wordDict. - אסור שישארו אותיות, ואי אפשר לשנות סדר או לדלג על אותיות.
- אותה מילה מהמילון יכולה לשמש יותר מפעם אחת.
- עונים רק כן או לא; לא צריך להחזיר את הפיצול.
דוגמה 1
Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true"leet" + "code".
דוגמה 2
Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true"apple" + "pen" + "apple": מילים יכולות לחזור.
דוגמה 3
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false"cats" + "and" וגם "cat" + "sand" משאירים "og", שהיא לא מילה.
אילוצים
1 <= s.length <= 3001 <= wordDict.length <= 10001 <= wordDict[i].length <= 20- כל המילים שונות ומכילות אותיות אנגליות קטנות.
רמזים
נתקעתם? פתחו רמז אחד בכל פעם. כל רמז מגלה קצת יותר מהקודם.
הרעיון במשפט אחד
לכל מיקום i במחרוזת, רושמים אם אפשר לפצל את i התווים הראשונים למילים: אפשר אם יש מילה מהמילון שנגמרת ב-i וגם את החלק שלפני המילה הזו היה אפשר לפצל.
הגישה הנאיבית (ולמה היא איטית)
רקורסיה: "מנסים כל מילה שמתאימה בהתחלה, ואז פותרים את השאר". הבעיה היא שאותה שארית נפתרת שוב ושוב. בדוגמה 3, "cats" + "and" ו-"cat" + "sand" מגיעים שניהם ל-"og". על מחרוזת כמו "aaaa…ab" עם המילים "a", "aa", "aaa", מספר דרכי הפיצול מתפוצץ, וכל אחת מהן נכשלת ב-b. זה זמן אקספוננציאלי.
התובנה המרכזית: רק המיקום חשוב
האם אפשר לפצל את שאר s תלוי רק באיפה אתם, לא באילו מילים הביאו אתכם לשם. אז יש רק n + 1 שאלות שונות לענות עליהן, אחת לכל מיקום. עונים על כל אחת פעם אחת ושומרים. זה תכנות דינמי (dynamic programming).
נגדיר canBreak[i] = "אפשר לפצל את i התווים הראשונים של s למילים":
canBreak[0] = true (the empty prefix: nothing to split)
canBreak[i] = true if, for some word w:
s has w ending exactly at position i, and
canBreak[i - w.length] is trueבמילים: המילה האחרונה בפיצול נגמרת ב-i; מה שבא לפניה חייב גם הוא להיות ניתן לפיצול. ממלאים את הטבלה מ-1 עד n ומחזירים canBreak[n].
צעד אחר צעד
s = "leetcode", wordDict = ["leet", "code"]:
i | i התווים הראשונים | מילה שנגמרת ב-i? | canBreak[i] |
|---|---|---|---|
| 0 | "" | (מקרה בסיס) | true |
| 1–3 | l, le, lee | אין | false |
| 4 | leet | leet (מתחילה ב-0, canBreak[0] ✓) | true |
| 5–7 | leetc … leetcod | אין | false |
| 8 | leetcode | code (מתחילה ב-4, canBreak[4] ✓) | true |
התשובה: canBreak[8] = true.
הקוד
הפתרון לדוגמה מופיע למטה, עם הערות על כל שורה חשובה.
כמה זה מהיר?
כש-n = האורך של s, W = מספר המילים ו-L = המילה הארוכה ביותר:
- זמן: O(n · W · L). לכל מיקום, מנסים כל מילה, והשוואה של מילה לוקחת עד
Lצעדים. - זיכרון: O(n) לטבלה.
טעויות נפוצות
- לקחת בחמדנות את המילה הראשונה (או הארוכה ביותר) שמתאימה. בדוגמה 3, גם
"cat"וגם"cats"נראות בסדר בהתחלה. רק בדיקה של כל אפשרות מגלה אם יש פיצול שעובד. - טעות באחד באינדקסים.
canBreak[i]מדבר עלiהתווים הראשונים, אז בטבלה ישn + 1ערכים, והמילה שנגמרת ב-iמתחילה ב-i - w.length. - לשכוח את
canBreak[0] = true. בלעדיו, שום דבר לא יכול להפוך ל-true.
להעמקה
- לשים את המילים ב-
Setולבדוק את תתי-המחרוזותs[j..i)לכלjב-20 המיקומים האחרונים (אורך המילה המקסימלי) היא דרך טובה באותה מידה לבדיקה הפנימית. - Word Break II מבקשת כל פיצול אפשרי, לא רק כן או לא. זה דורש backtracking, כשהטבלה הזו משמשת לדלג על מבויים סתומים.
פתרון לדוגמה
/**
* @param {string} s
* @param {string[]} wordDict
* @return {boolean}
*/
export default function wordBreak(s, wordDict) {
const canBreak = new Array(s.length + 1).fill(false)
// canBreak[i]: can the first i characters be split into words?
canBreak[0] = true // the empty prefix needs no words
for (let i = 1; i <= s.length; i++) {
// Try each word as the LAST word of the split, ending exactly at position i.
for (const word of wordDict) {
const start = i - word.length // where that word would begin
// It fits, the part before it can be split, and the letters really match.
if (start >= 0 && canBreak[start] && s.startsWith(word, start)) {
canBreak[i] = true
break // one way is enough
}
}
}
return canBreak[s.length]
}export default function wordBreak(s: string, wordDict: string[]): boolean {
const canBreak = new Array<boolean>(s.length + 1).fill(false)
// canBreak[i]: can the first i characters be split into words?
canBreak[0] = true // the empty prefix needs no words
for (let i = 1; i <= s.length; i++) {
// Try each word as the LAST word of the split, ending exactly at position i.
for (const word of wordDict) {
const start = i - word.length // where that word would begin
// It fits, the part before it can be split, and the letters really match.
if (start >= 0 && canBreak[start] && s.startsWith(word, start)) {
canBreak[i] = true
break // one way is enough
}
}
}
return canBreak[s.length]
}def word_break(s: str, word_dict: list[str]) -> bool:
# can_break[i]: can the first i characters be split into words?
# can_break[0] is True: the empty prefix needs no words.
can_break = [True] + [False] * len(s)
for i in range(1, len(s) + 1):
# Try each word as the LAST word of the split, ending exactly at position i.
for word in word_dict:
start = i - len(word) # where that word would begin
# It fits, the part before it can be split, and the letters really match.
if start >= 0 and can_break[start] and s.startswith(word, start):
can_break[i] = True
break # one way is enough
return can_break[len(s)]