Problem
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note:
- The same word in the dictionary may be reused multiple times in the segmentation.
- You may assume the dictionary does not contain duplicate words.
Example 1:
1 | |
Example 2:
1 | |
Example 3:
1 | |
Explanation 1
-
We can use recursion to solve this problem.
-
Before we start, we put all the strings from the array into a set so that we can have constant time of accessing the element.
-
Create a one dimensional array
memo[str.length]and initially set all elements are -1.memo[i]represents starting from index i of the string to the end, ifmemo[i]=0then it means the string[i:end] cannot be form from the set; ifdp[i]=1then it means string[i:end] can be formed from the set. -
For example, if string is
abcd, thenstartis from index 0. We first check ifacan be formed from the set, then we set the new start from b, and recursivly check if b can be found from the set, if yes, then we recursivly start fromc(we will use memo array later); else ifacannot be found from the set, then we check ifabcan be found from the set; ifabcan be found from the set, then we set the new start fromc(here start from c again, we will use a memo array to record if start from c the string can be found or not); ifabcannot be found from the set, then we checkabc. Repeat the previous step, until startstarthitsstr.length(). So, the recursive function will bememo[s]=set.contains(str[s:i)) && check(start=i). In other words, ifstring[s:i)is true andstring[i:]can also be found from the set, then the string starts from index 0 can be formed by the set.
Solution 1
1 | |
Explanation 2
-
We can also use dynamic programming to solve this problem. Dynamic state is a one dimensioanl array
dp, and it has lengthdp[s.length()+1]. It’s representd if thestring[0:i)can be formed by the set or not. -
Dynamic init is
dp[0] = truebecause if the string is empty, then it is inside the set. -
Dynamic function. For example,
string = "1234567", if we want to find if the string end at 5 (12345)dp[5]is inside the set, previously, we should already finishdp[0], dp[1], dp[2], dp[3], dp[4], then we can loop through these dps, so ifdp[0]is true and “12345” is inside the set, thendp[5]is true; else ifdp[1]is true and “2345” is inside the set thendp[5]is true; else ifdp[2]is true and “345” is inside the set, then we know dp[5] is true; In other word, we are using the previousdp[j]to count whetherdp[i]is true where j is from 0 to i-1. -
Dynamic result is the
dp[dp.length()-1]which is the string from index 0 to the last character of the string.
Solution 2
1 | |