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”.
给出一个字符串s,一个字典wordDict
问字符串s是否能分割成wordDict中的单词,字典中的单词可以重复使用,字典中不含重复单词
思路:
取每一段子串检查是否包含在字典中
每一段子串的方法:两个指针i, j,i = 0 ~ n(s的长度),j=0~i遍历substring(j , i)
字典可用HashSet
public boolean wordBreak(String s, List<String> wordDict) {
HashSet<String> hash = new HashSet<>(wordDict);
int n = s.length();
boolean[] dp = new boolean[n + 1];
dp[0] = true;
for(int i = 1; i <= n; i++) {
for(int j = 0; j < i; j++) {
if(dp[j] && hash.contains(s.substring(j, i))) {
dp[i] = true;
}
//注意不能用下面这种错误的方法,因为一个i对应很多j,dp[i]即使更新为true,后面只要有一个j为false,就会把之前的true覆盖掉
//dp[i] = dp[j] && hash.contains(s.substring(j, i)); //wrong
}
}
return dp[n];
}
也可以逐个判断substring是否和wordDict里面的单词相等,DFS
class Solution {
Boolean[] dp;
public boolean wordBreak(String s, List<String> wordDict) {
dp = new Boolean[s.length()];
return dfs(0, s, wordDict);
}
boolean dfs(int start, String s, List<String> wordDict) {
if(start >= s.length()) return true;
if(dp[start] != null) return dp[start]; //已经有结果,直接返回
boolean res = false;
for(String str : wordDict) {
if(s.length() - start < str.length()) continue; //当前单词不够长度,换下一个
if(s.substring(start, start+str.length()).equals(str) && dfs(start+str.length(), s, wordDict)) {
res = true;
break;
}
}
dp[start] = res;
return res;
}
}