LeetMotion
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.
We can solve this efficiently by working backward! For each character index, if we find a dictionary word that matches the characters starting exactly there, we check if the rest of the string can be broken down. If so, this index is also valid!
dp array of size len(s) + 1 with False. Set the base case dp[len(s)] = True (an empty string is always valid).i, try matching every word w in the dictionary.i, look ahead: does dp[i + len(w)] evaluate to True? If yes, set dp[i] = True and break early.dp[0] will store our answer!
Discussion
…