题目地址:
https://www.lintcode.com/problem/word-break-ii/description
给定一个字符串 s s s,再给定若干单词,求所有单词拼成字符串的方案,每个方案要求单词之间以空格分隔。
思路是DFS + 动态规划 + 字符串哈希。由于是求所有拼接方案,所以DFS是必要的。主要问题是如何提高效率和剪枝。DFS的时候,需要快速判断一开始切出来的字符串是否在单词列表里,同时也要快速判断切出来字符串后,
s
s
s的后面是否存在分割方案。前者可以用字符串哈希来加速(这里指的是将字符串看成
P
P
P进制数来哈希),后者可以先用动态规划预处理一下
s
s
s的后几个字符是否存在分割方案。具体来说:
1、由于在DFS的时候,我们需要枚举从某个位置开始向后切一段字符串,为了方便哈希值的计算,我们需要按照字符串从左到右是高位到低位来计算哈希值。所以在动态规划里,我们也需要按照这种顺序计算哈希值,并且之前计算所有单词的哈希值的时候,也要按这种顺序;
2、这个哈希值计算顺序定下来之后,就要考虑动态规划该如何递推。设
f
[
i
]
f[i]
f[i]表示
s
s
s的后
i
i
i个字符是否存在分割方案,则可以枚举
s
[
l
−
i
,
.
.
.
,
l
−
1
]
s[l-i,...,l-1]
s[l−i,...,l−1]的前缀是否存在,然后或上剩余字符串对应的
f
f
f值,这样枚举前缀的时候,哈希值仍然是按照从左到右从高位到低位计算的。
代码如下:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Solution {
private long HASH_SIZE = 31;
/*
* @param s: A string
* @param wordDict: A set of words.
* @return: All possible sentences.
*/
public List<String> wordBreak(String s, Set<String> wordDict) {
// write your code here
List<String> res = new ArrayList<>();
Set<Long> set = new HashSet<>();
for (String word : wordDict) {
long hash = 0;
// 从左到右从高位到低位计算哈希值
for (int i = 0; i < word.length(); i++) {
hash = hash * HASH_SIZE + word.charAt(i);
}
// 将哈希值存起来,方便判断一个字符串是否存在wordDict中
set.add(hash);
}
// s的后i个字符是否存在分割方案
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
// 枚举后i个字符
for (int i = 1; i <= s.length(); i++) {
long hash = 0;
// 枚举s的后i个字符的前缀长度
for (int j = 1; j <= i; j++) {
hash = hash * HASH_SIZE + s.charAt(s.length() - i + j - 1);
if (set.contains(hash) && wordDict.contains(s.substring(s.length() - i, s.length() - i + j))) {
dp[i] = dp[i - j];
// 发现能分割就立刻退出循环
if (dp[i]) {
break;
}
}
}
}
dfs(new StringBuilder(), 0, s, dp, set, wordDict, res);
return res;
}
private void dfs(StringBuilder sb, int pos, String s, boolean[] dp, Set<Long> set, Set<String> dict, List<String> res) {
if (pos == s.length()) {
// 记得要去掉末尾的空格
res.add(sb.substring(0, sb.length() - 1));
return;
}
long hash = 0;
// 枚举第一步切出s[pos: i]这一段
for (int i = pos; i < s.length(); i++) {
hash = hash * HASH_SIZE + s.charAt(i);
String cut = s.substring(pos, i + 1);
if (set.contains(hash) && dict.contains(cut) && dp[s.length() - pos]) {
sb.append(cut).append(' ');
dfs(sb, i + 1, s, dp, set, dict, res);
// 回溯恢复现场
sb.setLength(sb.length() - cut.length() - 1);
}
}
}
}
时间复杂度是指数级别的。空间 O ( l s + n ) O(l_s+n) O(ls+n), n n n是单词个数。