דילוג לתוכן הראשי
57

Word Break

בינוניdynamic programmingstrings

הקוד שלכם עדיין לא נשמר: רענון או יציאה מהדף מאפסים אותו. שמירת התקדמות תגיע יחד עם חשבונות משתמשים.

התרגיל הזה משתמש ב:1-D Dynamic Programmingקראו את המדריך למתחילים

בהינתן מחרוזת s ורשימת מילים wordDict, החזירו true אם אפשר לפצל את s לרצף של מילה אחת או יותר מהמילון, בלי שישאר כלום. כל מילה יכולה לשמש כמה פעמים שרוצים.

הבנת הבעיה

  • חותכים את s לחתיכות, וכל חתיכה חייבת להיות מילה מ-wordDict.
  • אסור שישארו אותיות, ואי אפשר לשנות סדר או לדלג על אותיות.
  • אותה מילה מהמילון יכולה לשמש יותר מפעם אחת.
  • עונים רק כן או לא; לא צריך להחזיר את הפיצול.

דוגמה 1

text
Input:  s = "leetcode", wordDict = ["leet", "code"]
Output: true

"leet" + "code".

דוגמה 2

text
Input:  s = "applepenapple", wordDict = ["apple", "pen"]
Output: true

"apple" + "pen" + "apple": מילים יכולות לחזור.

דוגמה 3

text
Input:  s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false

"cats" + "and" וגם "cat" + "sand" משאירים "og", שהיא לא מילה.

אילוצים

  • 1 <= s.length <= 300
  • 1 <= wordDict.length <= 1000
  • 1 <= 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 למילים":

    text
    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"]:

    ii התווים הראשוניםמילה שנגמרת ב-i?canBreak[i]
    0""(מקרה בסיס)true
    1–3l, le, leeאיןfalse
    4leetleet (מתחילה ב-0, canBreak[0] ✓)true
    5–7leetc … leetcodאיןfalse
    8leetcodecode (מתחילה ב-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, כשהטבלה הזו משמשת לדלג על מבויים סתומים.

    פתרון לדוגמה

    js
    /**
     * @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]
    }
    ts
    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]
    }
    python
    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)]