Level:
Medium
题目描述:
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.
Note:
- The same word in the dictionary may be reused multiple times in the segmentation.
- You may assume the dictionary does not contain duplicate words.
Example 1:
Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:
Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false
思路分析:
题目要求判断给出的字符串是否能由词典中的单词组成,我们应该用动态规划的思想去解决。但凡是能把问题规模缩小的都应该想到用动态规划求解。例如本题,如果我知道给定字符串的0到i子串可以用字典中的单词表达,那么我只需要知道i+1到末尾的子串能否被字典表达即可知道整个字符串能否被字典表达。所以随着i的增大,问题规模逐渐的缩小,且之前求解过的结果可以为接下来的求解提供帮助,这就是动态规划了。设dp[i]代表s.substring(0, i)能否被字典表达,此刻我们知道dp[0]~dp[i-1]的结果。而dp[i]的结果由两部分组成,一部分是dp[j](j < i),已知;另一部分是j到i之间的字符串是不是在字典里。当这两个部分都为真的时候,dp[i]即为真。而一旦dp[i]为真,就不用继续迭代了。测试的时候发现倒着遍历会比正着遍历速度稍稍快一点,大概是因为test case的字典里长度较长的单词要比长度较短的单词多。
代码:
public class Solution{
public boolean wordBreak(String s,List<String>wordDict){
if(s==null||s.length()==0)
return false;
boolean []dp=new boolean [s.length()+1]; //dp[i]表示字符串的前i个字符是否能由词典中的单词表示。
dp[0]=true;
for(int i=1;i<=s.length();i++){
for(int j=0;j<i;j++){
if(dp[j]&&wordDict.contains(s.substring(j,i))){
dp[i]=true;
break;
}
}
}
return dp[s.length()];
}
}