139. Word Break

Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.

Note that the same word in the dictionary may be reused multiple times in the segmentation.
 

Example 1:
Example 2:
Example 3:
Constraints:
  • 1 <= s.length <= 300
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 20
  • s and wordDict[i] consist of only lowercase English letters.
  • All the strings of wordDict are unique.

From: LeetCode
Link: 139. Word Break


Solution:

Ideas:
  • dp is initialized to false, except dp[0], which is true since an empty string can always be segmented.
  • For each position i in the string s, we check every word in wordDict.
  • If the length of the current word is less than or equal to i and the substring ending at i - wordLen can be broken down (i.e., dp[i - wordLen] is true), we compare the substring of s starting at i - wordLen and ending at i - 1 with the current word.
  • If they match, we set dp[i] to true and break out of the inner loop, as we have found a valid segmentation up to index i.
  • Finally, we return dp[n], which indicates whether the whole string can be segmented.
Code:
bool wordBreak(char* s, char** wordDict, int wordDictSize) {
    int n = strlen(s);
    bool dp[n + 1];
    memset(dp, 0, sizeof(dp));
    dp[0] = true; // base case: empty string

    for (int i = 1; i <= n; i++) {
        for (int j = 0; j < wordDictSize; j++) {
            int wordLen = strlen(wordDict[j]);
            if (wordLen <= i && dp[i - wordLen]) {
                if (strncmp(s + i - wordLen, wordDict[j], wordLen) == 0) {
                    dp[i] = true;
                    break;
                }
            }
        }
    }

    return dp[n];
}
11-26 06:05