0139. Word Break (M)
Word Break (M)
题目
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
题意
判断给定字符串按照某种方式分割后得到的所有子串能否在给定数组中找到。
思路
-
纯DFS会超时,所以利用Map记录下所有执行过的递归的结果。
-
动态规划。dp[i]代表s中以第i个字符结尾的子串是否满足要求,则状态转移方程为:只要有任意一个j(j<i)满足 dp[j]==true && wordDict.contains(s.substring(j,i))==true,那么dp[i]=true。
代码实现
Java
记忆化搜索
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
return isValid(s, 0, wordDict, new HashMap<>());
}
private boolean isValid(String s, int start, List<String> wordDict, Map<Integer, Boolean> record) {
if (start == s.length()) {
return true;
}
if (record.containsKey(start)) {
return record.get(start);
}
for (int end = start + 1; end <= s.length(); end++) {
if (wordDict.contains(s.substring(start, end)) && isValid(s, end, wordDict, record)) {
record.put(start, true);
return true;
}
}
record.put(start, false);
return false;
}
}
动态规划
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int i = 1; i <= s.length(); i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && wordDict.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}
JavaScript
/**
* @param {string} s
* @param {string[]} wordDict
* @return {boolean}
*/
var wordBreak = function (s, wordDict) {
let dp = new Array(s.length + 1).fill(false)
dp[0] = true
for (let i = 1; i <= s.length; i++) {
for (let j = 0; j < i; j++) {
if (dp[j] && wordDict.indexOf(s.slice(j, i)) >= 0) {
dp[i] = true
break
}
}
}
return dp[s.length]
}