forked from Adespinoza/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem_057.js
35 lines (30 loc) Β· 1.08 KB
/
problem_057.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* Breaks up string across lines to have max
* @param {string} s - input string
* @param {number} k - length of string
* @return {string[]}
*/
function breakString(s, k) {
const splitWords = s.split(' ');
const returnWords = [];
let currWords = [];
let currLength = -1;
for (let i = 0; i < splitWords.length; i++) {
const word = splitWords[i];
if (word.length > k) return null;
// Add word to list if less than/equal to k
if (currLength + word.length + 1 <= k) {
currWords.push(word);
currLength += word.length + 1;
} else {
returnWords.push(currWords.join(' '));
currWords = [word];
currLength = word.length;
}
}
returnWords.push(currWords.join(' '));
return returnWords;
}
console.log(breakString('the quick brown fox jumps over the lazy dog', 10)); // ["the quick", "brown fox", "jumps over", "the lazy", "dog"]
console.log(breakString('the quick brown fox jumps over the lazy dog', 15)); // ["the quick brown", "fox jumps over", "the lazy dog"]
console.log(breakString('the quick brown fox jumps over the lazy dog', 1)); // null