JSFiddle - React, Tailwind, and code Playground
JavaScript
// Given an input of a dictionary of words and an input senetnce that does not contain spaces, write a method that returns whether the input sentence can be split into words.
// Input: "bloombergisfun", ["bloom","bloomberg","is","fun"]
// Output: True // because "bloomberg is fun"
// Input: "bloombergisfun", ["bloom", "bloomberg","is"]
// Output: False
// Input: "bloombergisfun", ["bloom", "berg", "bloomberg","is","fun"]
// Output: True // because "bloom berg is fun"
const dict = ["bloom","bloomberg","is","fun"];
const sentenceSplit = (s, dict) => {
dict.sort((a, b) => { return b.length - a.length }).forEach(word => {
const start = s.indexOf(word);
if (start !== -1) {
const end = start + word.length;
s = s.replace(word, ` ${word} `);
}
});
return s.trim().replace(/ /g, ' ');
};
const sentenceSplit2 = (s, dict) => {
let left = 0;
let right = s.length - 1;
while (left < s.length && right > left) {
const word = s.substring(left, right + 1);
if (dict.indexOf(word) !== -1) {
s = s.replace(word, ` ${word} `);
left += word.length + 1 + 1;
right = s.length;
}
else {
right--;
}
}
return s.replace(/ /g, ' ').trim();
};
console.log(sentenceSplit('bloombergisfun', dict));
console.log(sentenceSplit2('bloombergisfun', dict));