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:
Input: s = "leetcode", wordDict = ["leet", "code"] Output: true Explanation: Return true because"leetcode"
can be segmented as"leet code"
.Example 2:
Input: s = "applepenapple", wordDict = ["apple", "pen"] Output: true Explanation: Return true because"
applepenapple"
can be segmented as"
apple pen apple"
. Note that you are allowed to reuse a dictionary word.Example 3:
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] Output: false
单词拆分。题意是给一个String s和一个包含一些单词的list,请你返回用这些list里面的单词是否能拼接成S。
思路是DP,DP[i]的含义是以字母i结尾的字符串是否能被list中的单词拼接。初始化dp[0] = true。接下来用另外一个指针j去扫描0 - i范围内的substring。如果dp[j] = true && substring(j, i)也在wordDict存在,则dp[i] = true。
跑一下第三个例子,
Example 1:
Input: s = "leetcode", wordDict = ["leet", "code"] Output: true Explanation: Return true because"leetcode"
can be segmented as"leet code"
.
DP数组最后的输出值如下,当i指针遍历到c(index = 4),j指针还在0的时候,此时因为dp[0] = true && s.substring(j, i) = s.substring(0, 4) = "leet"也存在于wordDict,所以可以将dp[4]标记为true。
[true, false, false, false, true, false, false, false, true]
时间O(n^2)
空间O(n)
Java实现
1 class Solution { 2 public boolean wordBreak(String s, List<String> wordDict) { 3 boolean[] dp = new boolean[s.length() + 1]; 4 dp[0] = true; 5 for (int i = 1; i <= s.length(); i++) { 6 for (int j = 0; j < i; j++) { 7 if (dp[j] && wordDict.contains(s.substring(j, i))) { 8 dp[i] = true; 9 break; 10 } 11 } 12 } 13 return dp[s.length()]; 14 } 15 }
JavaScript实现
1 /** 2 * @param {string} s 3 * @param {string[]} wordDict 4 * @return {boolean} 5 */ 6 var wordBreak = function (s, wordDict) { 7 const dp = new Array(s.length + 1).fill(false); 8 dp[0] = true; 9 for (let i = 1; i <= s.length; i++) { 10 for (let j = 0; j < i; j++) { 11 const word = s.slice(j, i); 12 if (dp[j] == true && wordDict.includes(word)) { 13 dp[i] = true; 14 break; 15 } 16 } 17 } 18 return dp[s.length]; 19 };