题目:Single Number
难度: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
解题思路:
* 使用动态规划
* 使用temp[i]代表s的前i个字符是否能被切割
* temp[i]=
* true :任意 j<i, (temp[j]=true)&&(s[j,i]属于wordDict)
* false:其他情况
代码如下:
public static boolean wordBreak(String s, List<String> wordDict) {
if(wordDict.size()==0) return false;
boolean[] dp = new boolean[s.length()+1];//在该位置之前是否是可行的,也就是该处可以加分隔符
dp[0] = true;//空字符串是true
for(int i=1;i<dp.length;i++){//求出dp[i] 也就是前i个字符 s[0]-s[i-1]
for(int j=i-1;j>=0;j--){
if(dp[j]){//前j个可以分割 s[0]-s[j-1]
String str = s.substring(j,i);
if(wordDict.contains(str)){
dp[i] = true;
break;
}
}
}
}
return dp[s.length()];
}