Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode"
,
dict = ["leet", "code"]
.
Return true because "leetcode"
can be segmented as "leet code"
.
分析:
给出一个字符串s和一个词典,判断字符串s是否可以被空格切分成一个或多个出现在字典中的单词。刚开始对这道题的理解有偏差,以为只要切出来的某一部分在字典里就可以了,后来发现不是这样,
这道题的意思是说,输入的字符串可以切成N段,每一段都必须在字典中。
举个例子:
s = "aaaaaaa",
dict = ["aaaa", "aa"],
返回false。
如果输入是
s = "aaab",
dict = ["a", "b"],
返回true。
初始化布尔型 数组, f[s.length() + 1],长度为s的长度加1, f[0, 1, 2, .......i - 1, i ] ,
f[i]表示的是字符串s从开始到第i个元素是否能用字典里的词表示。
遍历从开始到结尾的每个元素,先判断前半部分是否在字典里,再判断后面的是否在字典里。
public class Solution {
public boolean wordBreak(String s, Set<String> wordDict) {
if (s == null || s.length() == 0) {
return true;
}
int n = s.length();
boolean[] f = new boolean[n + 1];
//empty string is valid
f[0] = true;
for(int i=0; i<s.length(); i++){
if(f[i]){
for(int j=i+1; j<=s.length(); j++){
String sub = s.substring(i, j);
if(wordDict.contains(sub)){
f[j]=true;
}
}
}
}
return f[n];
}
}