Created
November 8, 2019 11:17
-
-
Save kulia26/e0c48a5112f86d45231229dfdd78a4a2 to your computer and use it in GitHub Desktop.
SMS sender
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
const solution = (S, K) => { | |
const words = S.split(' '); | |
if (words.some(word => word.length > K)) return -1; | |
let counter = 0; | |
while (words.length > 0) { | |
const firstWord = words.shift(); | |
let freeSpace = K - firstWord.length - 1; | |
if (words.length === 0 || freeSpace <= 0) { | |
counter++; | |
} | |
while (freeSpace > 0 && words.length > 0) { | |
if (words[0].length > freeSpace && words[0]) { | |
counter++; | |
freeSpace = -1; | |
} else { | |
const justOne = words.shift(); | |
freeSpace = freeSpace - justOne.length - 1; | |
if (freeSpace <= 0 || words.length === 0) { | |
counter++; | |
} | |
} | |
} | |
} | |
return counter; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment