You are provided with a string s and a set of words called wordDict. Write a function to determine whether s can be broken down into a sequence of one or more words from wordDict, where each word can appear more than once and there are no spaces in s. If s can be segmented in such a way, return true; otherwise, return false.
Input:
s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output:
false
Explanation: There is no valid segmentation of “catsandog” into dictionary words from wordDict.
Input:
s = "hellointerview", wordDict = ["hello","interview"]
Output:
true
Explanation: Return true because “hellointerview” can be segmented as “hello” and “interview”. Note that you are allowed to reuse a dictionary word.
Explanation
This solution uses bottom-up dynamic programming to solve the problem.
We create a boolean array dp of size n + 1 where n is the length of the input string. dp[i] is true if the first i characters of s can be segmented into a valid sequence of dictionary words. dp[0] is True because the empty string is a valid sequence - all other values are false to start.
def wordBreak(s, wordDict): wordSet = set(wordDict) dp = [False] * (len(s) + 1) dp[0] = True # Empty string is a valid break for i in range(1, len(s) + 1): for j in range(i): sub = s[j:i] if dp[j] and sub in wordSet: dp[i] = True break return dp[len(s)]
public boolean wordBreak(String s, List<String> wordDict) { Set<String> wordSet = new HashSet<>(wordDict); boolean[] dp = new boolean[s.length() + 1]; dp[0] = true; // Empty string is a valid break for (int i = 1; i <= s.length(); i++) { for (int j = 0; j < i; j++) { String sub = s.substring(j, i); if (dp[j] && wordSet.contains(sub)) { dp[i] = true; break; } } } return dp[s.length()];}
func wordBreak(s string, wordDict []string) bool { wordSet := make(map[string]bool) for _, word := range wordDict { wordSet[word] = true } dp := make([]bool, len(s)+1) dp[0] = true // Empty string is a valid break for i := 1; i <= len(s); i++ { for j := 0; j < i; j++ { sub := s[j:i] if dp[j] && wordSet[sub] { dp[i] = true break } } } return dp[len(s)]}
function wordBreak(s: string, wordDict: string[]): boolean { let wordSet: Set<string> = new Set(wordDict); let dp: boolean[] = new Array(s.length + 1).fill(false); dp[0] = true; // Empty string is a valid break for (let i = 1; i <= s.length; i++) { for (let j = 0; j < i; j++) { let sub: string = s.substring(j, i); if (dp[j] && wordSet.has(sub)) { dp[i] = true; break; } } } return dp[s.length];}
We then use a for-loop i which goes from 1 to n to iterate through the string. Inside the body of this loop, we determine the correct value for dp[i]. We do this by using another for-loop j, which goes from 0 to i and represents the start of the substring we are considering. If dp[j] is true and the substring from j to i (sub) is in the dictionary, then we have found a valid segmentation, and can therefore set dp[i] to True.
As soon as we find a valid segmentation, we can break out of the inner for-loop and move on to the next character in the string.
Finally, after we finished iterating, we return dp[n] which is the value of the last element in the array. This value will be True if the entire string can be segmented into valid dictionary words, and False otherwise.
Solution
Alternative Solution
An alternative solution follows the same bottom-up approach. We use the same for loop to iterate through the string, but instead of iterating over all substrings ending at i, we instead iterate over all words in the dictionary. If the current word matches the substring ending at i and if dp[i - word.length] is True, then we have found a valid segmentation and can set dp[i] to True.
def wordBreak(s, wordDict): dp = [False] * (len(s) + 1) dp[0] = True # Empty string is a valid break for i in range(1, len(s) + 1): for word in wordDict: if i >= len(word) and dp[i - len(word)]: sub = s[i - len(word):i] if sub == word: dp[i] = True break return dp[len(s)]
public boolean wordBreak(String s, List<String> wordDict) { boolean[] dp = new boolean[s.length() + 1]; dp[0] = true; // Empty string is a valid break for (int i = 1; i <= s.length(); i++) { for (String word : wordDict) { if (i >= word.length() && dp[i - word.length()]) { String sub = s.substring(i - word.length(), i); if (sub.equals(word)) { dp[i] = true; break; } } } } return dp[s.length()];}
func wordBreak(s string, wordDict []string) bool { dp := make([]bool, len(s)+1) dp[0] = true // Empty string is a valid break for i := 1; i <= len(s); i++ { for _, word := range wordDict { if i >= len(word) && dp[i-len(word)] { sub := s[i-len(word):i] if sub == word { dp[i] = true break } } } } return dp[len(s)]}
function wordBreak(s: string, wordDict: string[]): boolean { let dp: boolean[] = new Array(s.length + 1).fill(false); dp[0] = true; // Empty string is a valid break for (let i = 1; i <= s.length; i++) { for (let word of wordDict) { if (i >= word.length && dp[i - word.length]) { let sub: string = s.substring(i - word.length, i); if (sub === word) { dp[i] = true; break; } } } } return dp[s.length];}