|
| 1 | +// Naive solution. O(row*col). TLE |
| 2 | +class Solution { |
| 3 | + func wordsTyping(_ sentence: [String], _ rows: Int, _ cols: Int) -> Int { |
| 4 | + var (count, currentWordIndex) = (0, 0) |
| 5 | + for _ in 0..<rows { |
| 6 | + var col = -1 |
| 7 | + while col < cols { |
| 8 | + col += Array(sentence[currentWordIndex]).count |
| 9 | + if col < cols { |
| 10 | + col += 1 |
| 11 | + currentWordIndex += 1 |
| 12 | + if currentWordIndex >= sentence.count { |
| 13 | + currentWordIndex = 0 |
| 14 | + count += 1 |
| 15 | + } |
| 16 | + } |
| 17 | + } |
| 18 | + } |
| 19 | + return count |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +// DP. O(row*sentenceCount) |
| 24 | +class Solution { |
| 25 | + func wordsTyping(_ sentence: [String], _ rows: Int, _ cols: Int) -> Int { |
| 26 | + for word in sentence { |
| 27 | + if word.count > cols { |
| 28 | + return 0 |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + var memo = [Int:(Int, Int)]() // CurrentWordIndex: (SentenceCountInCurrentRow, StartingWordIndexOfNextRow) |
| 33 | + var (totalSentenceCount, currentRowStartWordIndex) = (0, 0) |
| 34 | + for _ in 0..<rows { |
| 35 | + if let (currentSentenceCount, nextRowStartWordIndex) = memo[currentRowStartWordIndex] { |
| 36 | + totalSentenceCount += currentSentenceCount |
| 37 | + currentRowStartWordIndex = nextRowStartWordIndex |
| 38 | + } else { |
| 39 | + var (currentCol, currentRowSentenceCount, currentIndex) = (0, 0, currentRowStartWordIndex) |
| 40 | + while currentCol < cols { |
| 41 | + let wordLen = Array(sentence[currentIndex]).count |
| 42 | + if currentCol + wordLen <= cols { |
| 43 | + currentCol += (wordLen + 1) |
| 44 | + currentIndex = (currentIndex + 1) % sentence.count |
| 45 | + if currentIndex == 0 { |
| 46 | + currentRowSentenceCount += 1 |
| 47 | + } |
| 48 | + } else { |
| 49 | + break |
| 50 | + } |
| 51 | + } |
| 52 | + totalSentenceCount += currentRowSentenceCount |
| 53 | + memo[currentRowStartWordIndex] = (currentRowSentenceCount, currentIndex) |
| 54 | + currentRowStartWordIndex = currentIndex |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return totalSentenceCount |
| 59 | + } |
| 60 | +} |
0 commit comments