Skip to content

Commit c35d51b

Browse files
committed
Add solution #418
1 parent dc20cb2 commit c35d51b

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,7 @@
406406
415|[Add Strings](./solutions/0415-add-strings.js)|Easy|
407407
416|[Partition Equal Subset Sum](./solutions/0416-partition-equal-subset-sum.js)|Medium|
408408
417|[Pacific Atlantic Water Flow](./solutions/0417-pacific-atlantic-water-flow.js)|Medium|
409+
418|[Sentence Screen Fitting](./solutions/0418-sentence-screen-fitting.js)|Medium|
409410
419|[Battleships in a Board](./solutions/0419-battleships-in-a-board.js)|Medium|
410411
420|[Strong Password Checker](./solutions/0420-strong-password-checker.js)|Hard|
411412
421|[Maximum XOR of Two Numbers in an Array](./solutions/0421-maximum-xor-of-two-numbers-in-an-array.js)|Medium|
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 418. Sentence Screen Fitting
3+
* https://leetcode.com/problems/sentence-screen-fitting/
4+
* Difficulty: Medium
5+
*
6+
* Given a rows x cols screen and a sentence represented as a list of strings, return the number
7+
* of times the given sentence can be fitted on the screen.
8+
*
9+
* The order of words in the sentence must remain unchanged, and a word cannot be split into two
10+
* lines. A single space must separate two consecutive words in a line.
11+
*/
12+
13+
/**
14+
* @param {string[]} sentence
15+
* @param {number} rows
16+
* @param {number} cols
17+
* @return {number}
18+
*/
19+
var wordsTyping = function(sentence, rows, cols) {
20+
const sentenceLength = sentence.length;
21+
const wordLengths = sentence.map(word => word.length + 1);
22+
let rowIndex = 0;
23+
let colIndex = 0;
24+
let wordIndex = 0;
25+
let result = 0;
26+
27+
while (rowIndex < rows) {
28+
if (colIndex + wordLengths[wordIndex] - 1 <= cols) {
29+
colIndex += wordLengths[wordIndex];
30+
wordIndex++;
31+
if (wordIndex === sentenceLength) {
32+
result++;
33+
wordIndex = 0;
34+
}
35+
} else {
36+
rowIndex++;
37+
colIndex = 0;
38+
}
39+
}
40+
41+
return result;
42+
};

0 commit comments

Comments
 (0)