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。
代码实现 - dfs+记录
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()];
}
}
本文深入探讨了WordBreak问题,一种常见的字符串分割问题,通过检查给定字符串是否能被分割成字典中的单词序列。文章提供了两种解决方案:使用DFS加记忆化搜索的方法避免重复计算,以及动态规划方法,通过构建DP数组优化查找过程。
1616

被折叠的 条评论
为什么被折叠?



