一、题目
二、代码
class Solution
{
public boolean wordBreak(String s, List<String> wordDict)
{
//满足下标的长度
int i,j;
int length = s.length();
int list_length = wordDict.size();
// StringBuilder str = new StringBuilder(s);
// System.out.println(" str " +str);
// //后面不包括
// System.out.println(" str " +str.substring(0,1));
boolean[] dp = new boolean[length+1];
dp[0] = true;
for(i=1;i<=length;i++)
{
// int temp_length = wordDict.get(i).length();
for(j=0;j<list_length;j++)
{
int string_length = wordDict.get(j).length();
//长度够且之前为真
if(i>=string_length&&dp[i-string_length]==true)
{
// System.out.println(" i " + i +" string_length " +string_length);
// System.out.println(" dp[i-string_length] " +dp[i-string_length]);
// System.out.println(" s.substring(i-string_length,i) " +s.substring(i-string_length,i));
// System.out.println(" wordDict.get(j) " + wordDict.get(j));
if(s.substring(i-string_length,i).equals( wordDict.get(j)) )
{
// System.out.println(i+" true ");
dp[i] = true;
}
}
// if()
}
}
// for(i=0;i<length;i++)
// {
// System.out.println(" i " +i+" dp[i] "+dp[i]);
// }
return dp[length];
}
}
三、运行结果
四、附录
二刷
class Solution
{
public boolean wordBreak(String s, List<String> wordDict)
{
int i,j;
int length = s.length();
boolean[] res = new boolean[length+1];
res[0] = true;
int size = wordDict.size();
//这样其实固定了顺序
// for(i=0;i<size;i++)
// {
// String temp = wordDict.get(i);
// int dict_length = temp.length();
// for(j=dict_length;j<=length;j++)
// {
// if(res[j-dict_length] == true &&s.substring(j-dict_length,j).equals(temp))
// {
// res[j] = true;
// }
// }
// }
for(i=0;i<=length;i++)
{
for(j=0;j<size;j++)
{
String temp = wordDict.get(j);
int dict_length = temp.length();
if(i<dict_length) continue;
if(res[i-dict_length] == true &&s.substring(i-dict_length,i).equals(temp)) res[i] = true;
}
}
//for(i=0;i<=length;i++) System.out.println(" "+i+" "+res[i]);
return res[length];
}
}