给出一个字符串s和一个词典,判断字符串s是否可以被空格切分成一个或多个出现在字典中的单词。
样例
给出
s = "lintcode"
dict = ["lint","code"]
返回 true 因为"lintcode"可以被空格切分成"lint code"
public class Solution {
/*
* @param s: A string
* @param dict: A dictionary of words dict
* @return: A boolean
*/
//方法一
//AC=100%
public boolean wordBreak(String s, Set<String> dict) {
if(s.length() == 0 && (dict == null || dict.size()==0)) return true;
if(s.length() == 0 || (dict == null || dict.size()==0)) return false;
//boolen比int占的空间小
boolean[] dp = new boolean[s.length()+1];
dp[0] = true;
for(int i = 0; i < s.length(); i++){
for(String str : dict){
if(dp[i] && i+str.length() <= s.length() && s.substring(i,i+str.length()).equals(str)) dp[i+str.length()] = true;
}
}
return dp[s.length()];
}
//方法二
//AC=92%
//超内存
//栈空间不够用了,递归次数太多
public boolean wordBreak_1(String s, Set<String> dict) {
int minLen=Integer.MAX_VALUE, maxLen=Integer.MIN_VALUE;
for(String sTmp:dict){
minLen = Math.min(minLen, sTmp.length());
maxLen = Math.max(maxLen, sTmp.length());
}
if(s.length()==0 && dict.size()==0)
return true;
if(s.length()==0 || dict.size()==0)
return false;
return helper(s, dict, minLen, maxLen);
}
String sub;
boolean helper(String s, Set<String> dict, int minLen, int maxLen){
for(int i=minLen; i<=maxLen; i++){
if(s.length()<i)
return false;
sub = s.substring(0, i);
if(dict.contains(sub)){
if(i==s.length())
return true;
if(helper(s.substring(i, s.length()), dict, minLen, maxLen))
return true;
}
}
return false;
}
//方法三
//AC=96%
//超内存
//SC = O(n)
public boolean wordBreak_2(String s, Set<String> dict) {
int n=s.length();
if(n==0 && dict.size()==0) return true;
//dp[i] = 长i的字符串能够切分
int[] dp = new int[n+1];
dp[0]=1;
for(int i=1; i<=n; i++){//长 i-1 的串
for(int j=i-1; j>=0; j--){
String sub = s.substring(j,i);
if(dp[j]==1 && dict.contains(sub)){
dp[i]=1;
break;
}
}
}
return dp[n]==1?true:false;
}
}