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.
Explanation:
判断一个完整的字符串能否分割成给定的字符串集,字符串集中的字符串可以重复使用。
My Thinking:
My Solution:
Optimum Thinking:
我们用dp[i]来表示s的第0-i个字符组成的字符串能被分割成若干个字段,且这些字段都在在字典中。
使用i遍历s中的每个字符,使用j在内循环中从0到i,即j将0-i分割成了0-j和j-i,如果0-j组成的字符串是字典内的且j-i组成的字符串也是字典内的,那么我们就将dp[i]=true,表示0-i可以分割成若干个字典内的字符串(一开始是两个,后面将两个看成一个整体,日后的0-j就是现在的0-i),不断更新dp[i]。
Optimum Solution:
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
//Second DP
for(int i=1; i <= s.length(); i++){
for(int j=0; j < i; j++){
if(dp[j] && dict.contains(s.substring(j, i))){
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}