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. You may assume the dictionary does not contain duplicate words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
public class Solution {
// shoudl consider input, wordDict is small, check through string s
// O(n*m) m for small Dict
public boolean wordBreak(String s, List<String> wordDict) {
boolean[] canBreak = new boolean[s.length() + 1]; // s can be break from start to i;
canBreak[0] = true;
for(int i=0; i<= s.length(); i++){
if(!canBreak[i]) continue;
for(String word : wordDict) { // renew each possible position with true
int len = word.length();
int end = i + len;
// those unreachable position and reached position should ignore
if(end > s.length() || canBreak[end]) continue;
if(s.substring(i,end).equals(word)){
canBreak[end] = true;
}
}
}
return canBreak[s.length()];
}
}
/*
//Second DP
put list<String> into Set<String>
O(n^2) time two nested for loop
O(K) for Dict
for(int i=1; i <= s.length(); i++){ // fix the ending, find the starting, then compare middle
for(int j=0; j < i; j++){
if(f[j] && dict.contains(s.substring(j, i))){
f[i] = true;
break;
}
}
}
*/
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。