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”.
UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
分析
没有思路时,首先要清楚分割出来的子串肯定要包含在List中,所以肯定需要一个判断的函数,那么接下来怎么分割呢。
假设先将字符串分成前后两串,从后向前分割稍微好理解一点,那么对于每个字母肯定都要这样去操作,所以有了第一层循环。
接下来我们先看后面的子串,我们需要判断后面的子串是否可以分割成字典中存在的单词,这里我们就需要以前判断过的记录再结合当前新加入的字母来做出决定,这就用到了动态规划的思想。对于后方子串的每个分子串,如果之前可以分割并且加入新字母的子串也存在于字典中,那么就说明后方子串可分割,直接跳出进入上一层的循环中。
至此,整个求解过程也就确定下来了。
补充
最初写了一个在List中查找String的私有方法,后来查了API后发现List自身有contains方法,contains方法会把List中的元素都遍历一遍。起初以为自己写的方法会快一点,但是从花费时间上来看contains更胜一筹。
Java实现
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
boolean[] dp=new boolean[s.length()+1];
dp[s.length()]=true;
for(int i=s.length()-1;i>=0;--i)
{
for(int j=i;j<s.length();++j)
{
String sub=s.substring(i,j+1);
if(wordDict.contains(sub)&&dp[j+1])
{
dp[i]=true;
break;
}
}
}
return dp[0];
}
private boolean containSubstring(String s,List<String> dict)
{
for(String d:dict)
{
if(d.equals(s))
{
return true;
}
}
return false;
}
}