ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

418. Sentence Screen Fitting

2021-07-05 02:00:25  阅读:221  来源: 互联网

标签:rows sentence int Screen cols start Fitting length 418


Given a rows x cols screen and a sentence represented as a list of strings, return the number of times the given sentence can be fitted on the screen.

The order of words in the sentence must remain unchanged, and a word cannot be split into two lines. A single space must separate two consecutive words in a line.

 

Example 1:

Input: sentence = ["hello","world"], rows = 2, cols = 8
Output: 1
Explanation:
hello---
world---
The character '-' signifies an empty space on the screen.

Example 2:

Input: sentence = ["a", "bcd", "e"], rows = 3, cols = 6
Output: 2
Explanation:
a-bcd- 
e-a---
bcd-e-
The character '-' signifies an empty space on the screen.

Example 3:

Input: sentence = ["i","had","apple","pie"], rows = 4, cols = 5
Output: 1
Explanation:
i-had
apple
pie-i
had--
The character '-' signifies an empty space on the screen.

 1 public class Solution {
 2     public int wordsTyping(String[] sentence, int rows, int cols) {
 3         String s = String.join("_", sentence) + "_";
 4         int len = s.length();
 5         int count = 0;
 6         int[] map = new int[len];
 7         for (int i = 1; i < len; ++i) {
 8             // if charAt(i) == '_', which means we saved an extra space
 9             map[i] = s.charAt(i) == '_' ? 1 : map[i-1] - 1;
10         }
11         for (int i = 0; i < rows; ++i) {
12             count += cols;
13             count += map[count % len];
14         }
15         return count / len;
16     }
17 }
 1     public int wordsTyping(String[] sentence, int rows, int cols) {
 2         String s = String.join(" ", sentence) + " ";
 3         int start = 0;
 4         int length = s.length();
 5         for (int i = 0; i < rows; i++) {
 6             start += cols;
 7             if (s.charAt(start % length) == ' ') {
 8                 start++;
 9             } else {
10                 while (start >= 0 && s.charAt(start % length) != ' ') {
11                     start--;
12                 }
13                 start++;
14             }
15         }
16         
17         return start / length;
18     }

 

标签:rows,sentence,int,Screen,cols,start,Fitting,length,418
来源: https://www.cnblogs.com/beiyeqingteng/p/14970589.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有