Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
For example, given
s = "leetcode",
dict = ["leet", "code"].
public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = s.length() - 1; i >= 0; i--){
String sub = s.substring(i);
if (dict.contains(sub)){
list.add(i);
}else {
for (Integer index : list){
sub = s.substring(i, index);
if (dict.contains(sub)){
list.add(i);
break;//刚开始的时候把这个漏掉了,会造成很奇怪的事情发生,因为这个时候list的内容发生变化了
}
}
}
}
if (list.size() == 0){
return false;
}
return list.get(list.size() - 1) == 0;
}
}