Skip to content

Instantly share code, notes, and snippets.

@apparition47
Created December 7, 2019 13:19
Show Gist options
  • Save apparition47/ac24de63911cf8b5734030413158141f to your computer and use it in GitHub Desktop.
Save apparition47/ac24de63911cf8b5734030413158141f to your computer and use it in GitHub Desktop.
LeetCode 418 Sentence Screen Fitting

Given a rows x cols screen and a sentence represented by a list of non-empty words, find how many times the given sentence can be fitted on the screen.

Note:

  1. A word cannot be split into two lines.
  2. The order of words in the sentence must remain unchanged.
  3. Two consecutive words in a line must be separated by a single space.
  4. Total words in the sentence won’t exceed 100.
  5. Length of each word is greater than 0 and won’t exceed 10.
  6. 1 ≤ rows, cols ≤ 20,000.

Example 1:

Input:
rows = 2, cols = 8, sentence = ["hello", "world"]

Output: 
1

Explanation:
hello---
world---

The character '-' signifies an empty space on the screen.

Example 2:

Input:
rows = 3, cols = 6, sentence = ["a", "bcd", "e"]

Output: 
2

Explanation:
a-bcd- 
e-a---
bcd-e-

The character '-' signifies an empty space on the screen.

Example 3:

Input:
rows = 4, cols = 5, sentence = ["I", "had", "apple", "pie"]

Output: 
1

Explanation:
I-had
apple
pie-I
had--

The character '-' signifies an empty space on the screen.
function * sent(sentence) {
while (1) {
for (i=0; i<sentence.length; i++) {
yield sentence[i]
}
}
}
const fits = (rows, cols, sentence) => {
let placements = 0
let scr = ""
let sen = sent(sentence)
let r=0
while (r<rows) {
let next = sen.next().value
if (next.length == cols-scr.length) { // matching
scr += next
r++
} else if ((next.length+1) <= (cols-scr.length)) {
scr += next + " "
} else { // no room, go to next line
scr = ""
r++
}
if (next === sentence[sentence.length-1] && rows != r) {
placements++
}
}
return placements
}
// driver
let result
result = fits(3,6,["a","bcd", "e"])
console.log("res:",result) // 2
result = fits(4,5,["I", "had", "apple", "pie"])
console.log("res:",result) // 1
result = fits(2,8,["hello","world"])
console.log("res:",result) // 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment