首页 > 代码库 > leetcode算法 - Word Break II js实现

leetcode算法 - Word Break II js实现

题目如下:
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

Return all such possible sentences.


For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].


A solution is ["cats and dog", "cat sand dog"].

思路:用数组构造一个hashmap,用数组模拟栈模型, 用栈模型实现dps(深度优先算法)。

核心代码:

function solve(start){
var childMap=map[hash(start)];
var childMapLength=childMap.length;
for(var i=0;i<childMapLength;i++){
stack.push(childMap[i]);
if(childMap[i].finish===s.length){ //正确答案
answer.push(stringify(stack))
}else{
solve(childMap[i].finish); //递归
}
stack.pop();
}
}
solve(0);

测试结果
dict:

技术分享

s=“abcdefghijk”

result:

技术分享

 

leetcode算法 - Word Break II js实现