1 题目理解
140与130的区别是,当字符串可分的时候,要求返回具体的分割字符串。
2 回溯+记忆化
对于字符串s,如果前面一部分是单词列表中的词,则拆分出这个单词,右边的继续分割。
分割过程中,对起始下标i,已经分割过的,用map缓存。
使用字典树也可以加快搜索速度。
class Solution {
private Trie trie;
private List<String> result;
public List<String> wordBreak(String s, List<String> wordDict) {
int n = s.length();
trie = new Trie();
trie.initWord(wordDict);
result = new ArrayList<String>();
dfs(s,0);
return cache.get(0);
}
private Map<Integer,List<String>> cache = new HashMap<Integer,List<String>>();
private void dfs(String s, int i){
if(i>=s.length()){
return;
}
if(cache.get(i)!=null) return;
List<String> r = new ArrayList<String>();
for(int x = i+1;x<=s.length();x++){
String left = s.substring(i,x);
if(trie.find(left)){
dfs(s,x);
if(cache.get(x)!=null){
for(String right : cache.get(x)){
r.add(left+" "+right);
}
}else{
r.add(left);
}
}
}
cache.put(i,r);
}
}
class Trie{
private TrieNode root = new TrieNode('/');
public void initWord(List<String> wordDict){
for (String word : wordDict){
addWord(word);
}
}
public boolean find(String word){
TrieNode node = root;
for(int i=0;i<word.length();i++){
int index = word.charAt(i) - 'a';
if(node.children[index]==null){
return false;
}
node = node.children[index];
}
return node.end;
}
private void addWord(String word) {
TrieNode node = root;
for(int i=0;i<word.length();i++){
int index = word.charAt(i) - 'a';
if(node.children[index]==null){
node.children[index] = new TrieNode(word.charAt(i));
}
node = node.children[index];
}
node.end = true;
}
class TrieNode{
TrieNode[] children = new TrieNode[26];
boolean end;
private char data;
public TrieNode(char data){
this.data = data;
}
}
}
补充:也可以在139的基础上做。在找到0到i可以分割的时候,记录下分割方式。当然这种方法也可以加上Trie树。
class Solution {
public List<String> wordBreak(String s, List<String> wordDict) {
Map<Integer,List<String>> resultMap = new HashMap<Integer,List<String>>();
int n = s.length();
boolean[] dp = new boolean[n+1];//从0到i可以被分解
dp[0] = true;
for(int i=1;i<=n;i++){
resultMap.put(i, new ArrayList<String>());
for(int j=0;j<i;j++){
if(dp[j]==true && wordDict.contains(s.substring(j,i))){
dp[i]=true;
if(j==0){
resultMap.get(i).add(s.substring(j,i));
}else{
for(String pre:resultMap.get(j)){
resultMap.get(i).add(pre+" "+s.substring(j,i));
}
}
}
}
}
return resultMap.get(n);
}
}