leetcode算法 - Word Break II js实现

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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实现的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-139-Word Break

LeetCode 139. Word Break

Java Word Break(单词拆解)

[LeetCode] 139 Word Break

leetcode笔记:Word Break

LeetCode - Word Break