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.
    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.

思路
假设string是无限循环下去的,需要记录所有row走完会move到哪里。用start指针的值记录一共在screen上有多少字符。最后通过start / sentence length即可知道一共能打印下多少个sentence。

具体包含以下步骤:

  1. 先把sentence连起来,然后摊平。例如:[“abc”, “de”, “f”],连成sentence是”abc de f “,设想这个sentence无限循环,就是”abc de f abc de f abc de f abc…”
  2. 用start pointer记录每一行的start,每多一个row,把pointer往后移动cols个。
  3. 移动pointer时两种情况需要处理一下:
    • 一行的开头刚好是space,start指针直接+1,即remove一个space
    • 一行的开头刚好是一个word的中间,start需要退回到该word的开头,即在上一行增加一些space。
class Solution {
    public int wordsTyping(String[] sentence, int rows, int cols) {
        String allSentence = "";
            
        //1. reorganized the sentence using " "
        for (String word : sentence) {
            allSentence += word + " ";
        }
        int len = allSentence.length();
        
        //2. calculate the start pointer
        int start = 0;
        
        for (int i = 0; i < rows; i++) {
            start = start + cols;
            if (allSentence.charAt(start % len) == ' ') {
                start++;
            } else {
                while (start > 0 && allSentence.charAt((start - 1) % len) != ' ') {
                    start--;
                }
            }
        }
        
        return start / len;
    }
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 四.苦恼 兰子起个大早,想去梅子家看看。可等待她的是铁将军把门,敲门,也没有人应答。兰子一脸纳闷,人都到哪去了,这...
    上善若水1980阅读 383评论 0赞 0
  • 最近,气温一降再降,虽身在南方,相比北方再冷也不过如此,但南方的冷不仅仅是温度计上的个位数,还带一点点潮湿,这样的...
    亦沁阅读 198评论 0赞 0
  • 文章谈到的最近热播的《我的前半生》罗子君被出轨那桥段吧,作为好友的唐晶好言相劝反而招到罗子君的抱怨。质疑“到底...
    控心_ebed阅读 319评论 0赞 2
  • 那躺着一具尸体 不 是一个人 我将他叫醒 停顿片刻 他牵强的笑 而后颤抖走着 不知是哪个方向 ...
    Breeze子凡阅读 291评论 0赞 0

友情链接更多精彩内容