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"
.
原题链接:https://oj.leetcode.com/problems/word-break/
题目:给定一个字符串和一个单词词典,推断字符串是否能被切分成空格隔开的存在于词典中的单词序列。
思路:从头開始依次一个字符地向后截取并推断。逻辑应该是对的。測试超时了。
public static boolean wordBreak1(String s, Set<String> dict) {
if(dict.size() <= 0)
return false;
int len = s.length();
if(len <= 0)
return true;
boolean flag = false;
for(int i=1;i<=len;i++){
String tmp = s.substring(0, i);
if(dict.contains(tmp)){
if(tmp.length() == len)
return true;
}
flag = wordBreak(s.substring(i),dict);
}
return flag;
}
动态规划。
//dp[i] 代表 字符串(j,i)能被分词否
public static boolean wordBreak(String s, Set<String> dict) {
int length = s.length();
boolean[] dp = new boolean[length + 1];
dp[0] = true;
for (int i = 1; i <= length; i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && dict.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[length];
}