Skip to content

Instantly share code, notes, and snippets.

@agaase
Created May 16, 2017 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agaase/e37fb3b3b05cdbf24e22cb91c087d4da to your computer and use it in GitHub Desktop.
Save agaase/e37fb3b3b05cdbf24e22cb91c087d4da to your computer and use it in GitHub Desktop.
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.
//http://practice.geeksforgeeks.org/problems/word-break-part-2/0
var candidates = [];
var dict = ["snake", "snakes", "and", "sand", "ladder"];
var input = "snakesandladder";
for(var i=0;i<input.length;i++){
debugger;
var chAtI = input.charAt(i);
if(candidates.length){
for(var j=0;j<candidates.length;j++){
candidates[j][candidates[j].length-1] = candidates[j][candidates[j].length-1]+chAtI;
if(dict.indexOf(candidates[j][candidates[j].length-1])>-1){
candidates[j].push("");
}
}
}
if(dict.indexOf(input.substring(0,i+1))>-1){
candidates.push([input.substring(0,i+1),""]);
}
}
for(var i=0;i<candidates.length;i++){
if(candidates[i][candidates[i].length-1]==""){
console.log(candidates[i]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment