public class Solution {
public List<String> wordBreak(String s, Set<String> dict) {
boolean breakable[] = new boolean[s.length()+1];
breakable[0] = true;
for(int i = 1; i <= s.length(); i++)
{
for(int j = 0; j <= i; j++)
{
if(breakable[j] && dict.contains(s.substring(j,i)))
{
breakable[i] = true;
break;
}
}
}
if(!breakable[s.length()])
return new ArrayList();
List[] breaks = new List[s.length()];
for(int i = 0; i < s.length(); i++)
{
breaks[i] = new ArrayList();
for(int j = 0; j <= i; j++)
{
if(dict.contains(s.substring(j,i+1)))
{
if(j == 0)
{
breaks[i].add(s.substring(j,i+1));
}
else
{
for(String tmp : (List<String>)breaks[j-1])
{
breaks[i].add(tmp + " " + s.substring(j, i+1));
}
}
}
}
}
return breaks[s.length()-1];
}
}
[leetcode] work break II
最新推荐文章于 2024-08-28 19:47:50 发布