For example, given
s ="leetcode",
dict =["leet", "code"].
Return true because"leetcode"can be segmented as"leet code".
public class WordBreak
{
//切割字符串
public static boolean wordBreak1(String s, Set<String> dict)
{
int _len = s.length();
for(int i = 0; i < _len; ++i)
{
if(i == 0)
{
if(dict.contains(s.substring(0, _len)))
return true;
}
else
{
if (dict.contains(s.substring(0, i)) && dict.contains(s.substring(i, _len)))
return true;
}
}
return false;
}
//动态规划
//状态转移方程 f(n) = f(m) && c(m + 1, n)
//f(n)表示前n个字符是否可分,c(m + 1, n)表示字典中是否包含第m+1到第n个字符的字符串
public static boolean wordBreak2(String s, Set<String> dict)
{
int _len = s.length();
boolean[] _arrays = new boolean[_len + 1];
_arrays[0] = true;
for(int i = 1; i <= _len; ++i)//i对应方程中的n
{
for(int j = 0; j < i; ++j)//j对应方程中的m
{
if(_arrays[j] && dict.contains(s.substring(j, i)))
{
_arrays[i] = true;
}
}
}
return _arrays[_len];
}
}