Skip to content

Instantly share code, notes, and snippets.

@malisetti
Last active December 19, 2018 10:47
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 malisetti/67bb3ffb725b8c92a6149c9306727929 to your computer and use it in GitHub Desktop.
Save malisetti/67bb3ffb725b8c92a6149c9306727929 to your computer and use it in GitHub Desktop.
"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