[LeetCode 418] Sentence Screen Fitting

给定一个屏幕和一个由非空单词组成的句子,找出能在屏幕上显示的句子数量。题目要求保持单词顺序不变,且每行不超过一定列数。分析问题后,可以通过一行一行处理并统计有效字符来优化解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Example

Example 1:
	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.
	
Example 2:
	Input:  rows = 2, cols = 8, sentence = ["hello", "world"]
	Output:  1
	
	Explanation:
	
	hello---
	world---
	
	The character '-' signifies an empty space on the screen.

Example 3:
	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.

Notice

  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.

 

分析

这道题刚开始的时候一定想到的就是常规的解法,我们尝试向每一行里一个个的塞入单词,如果一个单词塞不进去了就另起一行,最终计算我们总共塞了多少个单词,然后除以sentence的长度就是最终结果。

这种解法在面临  cols >> setences总长度时,会超时。因为sentence组成的字符串的总长度远远小于cols,导致每一行都需要大量的时间。那么这一题能否一行一行的去处理呢?

其实最终我们求得结果时,是想知道最终遍历了多少次sentence,这样可以求得最终的次数。首先把sentences进行处理,将其利用空格做分隔符组成一个字符串s。那么我们就可以把这一题转化为我们处理完所有的rows和cols后,看看总共塞进去了多长的s的有效字符。对于每一行,直接尝试从当前在s中的偏移位置+ cols,如果此时的字符是空格,说明这一行恰好可以放入cols个字符串,但是由于我们的s都是以空格做分割的,我们需要把s后面的这个空格也统计进去,所以这一行我们就放了cols + 1个字符串;如果此时的字符是单词的字符,那么说明这一行没有放满,就向前寻找第一个是空格的位置,然后继续。

Code

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
        int len = sentence.size();
        
        string s;
        for (int i = 0; i < sentence.size(); i ++)
        {
            s += sentence[i];
            s += " ";
        }
        
        
        int sLen = s.size();
        int start = 0;
        for (int i = 0; i < rows; i ++)
        {
            start += cols;
            if (s[start%sLen] == ' ')
            {
                start ++;
            }
            else
            {
                while (start > 0 && s[(start-1)%sLen] != ' ')
                {
                    start --;
                }
            }
        }
        
        return start/sLen;
    }
};

运行效率

Your submission beats 99.48% Submissions!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值