Last active
December 19, 2018 10:47
-
-
Save malisetti/67bb3ffb725b8c92a6149c9306727929 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
const s = "abppplee"; | |
const D = ["able", "ale", "apple", "bale", "kangaroo"]; | |
(() => { | |
// console.log(inline(s, D[4])); | |
const letterPositions = toCharMap(s); | |
D.sort((a, b) => { | |
return b.length - a.length; | |
}); | |
for (let i = 0; i < D.length; i++) { | |
const word = D[i]; | |
let pos = 0; | |
let found = false; | |
for (let j = 0; j < word.length; j++) { | |
const letter = word.charAt(j); | |
if (!letterPositions[letter]) { | |
break; | |
} | |
const possiblePositions = letterPositions[letter].map(p => p >= pos); | |
if (possiblePositions.length == 0) { | |
break; | |
} | |
pos = possiblePositions[0] + 1; | |
if (j == word.length - 1) { | |
found = true; | |
} | |
} | |
if (found) { | |
console.log(word); | |
break; | |
} | |
} | |
})(); | |
function toCharMap(str) { | |
const charMap = {}; | |
for (let i = 0; i < str.length; i++) { | |
const c = str.charAt(i); | |
if (!charMap[c]) { | |
charMap[c] = [i]; | |
} else { | |
charMap[c].push(i); | |
} | |
} | |
return charMap; | |
} | |
function inline(str1, str2) { | |
let x = 0; | |
for (let i = 0; i < str2.length; i++) { | |
const c = str2.charAt(i); | |
const p = str1.indexOf(c); | |
if (p === -1 || p < x) { | |
return -1; | |
} | |
x++; | |
} | |
return x; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment