[lintcode]889. Sentence Screen Fitting

链接:http://www.lintcode.com/zh-cn/problem/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.

 注意事项

  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.

您在真实的面试中是否遇到过这个题?

Yes

样例

Given rows = 2, cols = 8, sentence = ["hello", "world"], retrun 1.

Explanation:
hello---
world---

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

Given rows = 3, cols = 6, sentence = ["a", "bcd", "e"], return 2.

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

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

Given rows = 4, cols = 5, sentence = ["I", "had", "apple", "pie"], return 1.

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

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

思路

 

这道题给我们了一个句子,由若干个单词组成,然后给我们了一个空白屏幕区域,让我们填充单词,前提是单词和单词之间需要一个空格隔开,而且单词不能断开,如果当前行剩余位置放下不下某个单词,则必须将该单词整个移动到下一行。我刚开始想的是便利句子,每个单词分别处理,但是这种做法很不高效,因为有可能屏幕的宽度特别大,而单词可能就一两个,那么我们这样遍历的话就太浪费时间了,应该直接用宽度除以句子加上空格的长度之和,可以快速的得到能装下的个数。下面这种方法设计的很巧妙,思路是用totallen变量来记录下能装下的句子的总长度(在totallen 里面,句子和句子之间仅相差一个空格),最后除以一个句子的长度,就可以得到个数。而句子的总长度的求法时要在每个单词后面加上一个空格,我们遍历屏幕的每一行,然后每次totallen都加上宽度,然后看all[totallen%len]是否为空格,是的话就totallen加1,这样做的好处是可以处理末尾是没有空格的情况,比如宽度为1,只有一个单词a,那么我们都知道是这样放的 a ,totallen变为1,len是2,all[totallen%len]是空格,所以totallen自增1,变成2,这样我们用totallen/len就知道能放下几个了。对于all[totallen%len]不为空格的情况,如果all[(totallen-1)%len]也不为空格,那么totallen就自减1,进行while循环,直至其为空格为止。

 

 

class Solution {
public:
    /**
     * @param sentence: a list of string
     * @param rows: an integer
     * @param cols: an integer
     * @return: return an integer, denote times the given sentence can be fitted on the screen
     */
    int wordsTyping(vector<string> &sentence, int rows, int cols) {
        // Write your code here
        string all="";
        for(auto s:sentence)
            all+=(s+" ");
        int totallen=0;
        int len=all.size();
        for(int i=0;i<rows;i++)
        {
            totallen+=cols;
            if(all[totallen%len]==' ')
            {
                totallen++;
            }
            else
            {
                while(totallen>0 && all[(totallen-1)%len]!=' ')
                {
                    totallen--;
                }
            }
        }
        return totallen/len;
    }
};

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值