码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode算法 - Word Break II js实现

时间:2017-06-04 18:43:42      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:star   dict   const   pos   dog   bre   深度   算法   img   

题目如下:
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实现

标签:star   dict   const   pos   dog   bre   深度   算法   img   

原文地址:http://www.cnblogs.com/sha256/p/6940880.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!