Created
August 23, 2023 18:38
-
-
Save primaryobjects/3642040c2d61ac348717b9b751c4cb89 to your computer and use it in GitHub Desktop.
Sentence split https://jsfiddle.net/6msy9wpc/
This file contains hidden or 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
| // Given an input of a dictionary of words and an input senetnce that does not contain spaces, write a method that returns the input sentence split into words. | |
| // Input: "applesauceisfun", ["apple","applesauce","is","good"] | |
| // Output: "applesauce is fun" | |
| const dict = ["apple","applesauce","is","good"]; | |
| // Simple approach with indexOf (uses shorter words). | |
| 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, ' '); | |
| }; | |
| // Sliding window approach, finds longest fitting dictionary word. | |
| 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('applesauceisgood', dict)); | |
| console.log(sentenceSplit2('applesauceisgood', dict)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment