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. You may assume the dictionary does not contain duplicate words.
For example, given
s = “leetcode”,
dict = [“leet”, “code”].
Return true because “leetcode” can be segmented as “leet code”.
题意:给定一个字符串和一个字符串数组,问这个字符串能否正好被这个数组里的word分割。
思路:
第一个思路想到的是深度优先搜索,从头开始寻找每种可能的分割方案,直到找到一个正好分割的方案,返回true。
public boolean wordBreak(String s, List<String> wordDict) {
if (s == null || s.length() == 0) {
return true;
}
HashSet<String> set = new HashSet<>();
for (String word : wordDict) {
set.add(word);
}
return dfs(s, 0, set);
}
private boolean dfs(String s, int start, HashSet<String> set) {
if (start == s.length()) {
return true;
}
for (int i = start + 1; i <= s.length(); i++) {
String str = s.substring(start, i);
if (!set.contains(str)) {
continue;
}
if (dfs(s, i, set)) {
return true;
}
}
return false;
}
提交后,leetcode提示超时,看到relate topic提示是动态规划方法。
于是从这个角度想到了这个解法,dp[k]表示从头开始到第k个字符的字符串能否被dict完美break,dp[0]默认为true,可理解为空字符串能够被break。
求解dp[k]是否为true,只需要看0<=i<k这个范围是否存在某处使得dp[i] == true并且s.substring(i, k)在dict中。
从dp[1]开始迭代求出dp[s.length()],最后就看dp[s.length()]是否为true。
public boolean wordBreak1(String s, List<String> wordDict) {
if (s == null || s.length() == 0) {
return true;
}
HashSet<String> set = new HashSet<>();
for (String word : wordDict) {
set.add(word);
}
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int end = 1; end <= s.length(); end++) {
for (int start = 0; start < end; start++) {
if (dp[start] && set.contains(s.substring(start, end))) {
dp[end] = true;
break;
}
}
}
return dp[s.length()];
}