LeetCode 418. Sentence Screen Fitting
来源:互联网 发布:ps命令详解 linux 编辑:程序博客网 时间:2024/06/12 21:01
Given a rows x cols screen and a sentence represented by a list of words, find how many times the given sentence can be fitted on the screen.
Note:
A word cannot be split into two lines.
The order of words in the sentence must remain unchanged.
Two consecutive words in a line must be separated by a single space.
Total words in the sentence won’t exceed 100.
Length of each word 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.
s思路1:
1. 参考了http://www.cnblogs.com/grandyang/p/5975426.html
2. 自己也思考了下,肯定不能一个单词一个单词来放,太低效率。注意到,这类题,涉及到两个对象,一是有单词组成的句子,另一个是2维矩阵。要求是把句子放进矩阵里,计算可以放进去多少同样的句子?这就容易误导我们,认为方法就是去找每句话在矩阵中结束的位置坐标。除此之外,还可以反过来思考,根据矩阵的尺寸,找到每行开始坐标对应的完整句子(包括空格)中的位置,即:两种方法比较如下:
3. 具体做法:先组成句子,由给定的word+空格组成;在每一行开始都加上这一行的长度,得到总的长度数,最后再将总的长度除以每句话的长度就可以得到可以装下的句子数量!这里,要考虑两个特殊情况,都是因为边界引起的:在每行开始的位置,如果总长度%每句长度的结果刚好是一个句子的空格位置,那么可以把后面的句子都往前挪动一个位置以期望放得更多的句子,因为规定每行开始不能有空格,例如:
句子: a-bcd-e- (8个字符)
矩阵:
第二行开始的总坐标=0+5, sentence[5]=空格,就需要把后面的单词都往前挪一位,即:
这种情况在数学上(或代码上)可以把总坐标+1来模拟。
第二种情况是:单词不允许break,夸越两行。所以如果每行开头不是空格,我们还需要判断(总长度-1)%每句长度的位置是否是空格,不是空格,我们就要浪费一个位置,即:多一个位置放空格,如上表。这种情况在数学上(或代码上)可以把总坐标-1来模拟。
//方法1:int wordsTyping(vector<string>& sentence, int rows, int cols) { // string withspace="";//""代表string for(auto&word:sentence) withspace+=(word+"");//""代表string int start=0,len=withspace.size(); for(int i=0;i<rows;i++){ start+=cols; if(withspace[start%len]==' ')//每行开头不能有空格//' '代表char start++; else{ while(start>0&&withspace[(start-1)%len]!=' ')//每个单词不能break//' '代表char start--; } } return start/len;}
- Leetcode-418. Sentence Screen Fitting
- LeetCode 418. Sentence Screen Fitting
- [leetcode] 418. Sentence Screen Fitting 解题报告
- [Leetcode] 418. Sentence Screen Fitting 解题报告
- 418. Sentence Screen Fitting
- LeetCode 418. Sentence Screen Fitting 调整屏幕上的句子
- 418 Sentence Screen Fitting
- Sentence Screen Fitting
- LeetCode | 734. Sentence Similarity
- LeetCode # 737 Sentence Similarity II
- sentence
- Sentence
- Leetcode算法学习日志-737 Sentence Similarity II
- Curve Fitting
- over-fitting
- Exponential Fitting
- RANSAC Fitting
- Screen
- BIOS中断大全
- zoj1301
- zoj1629
- zoj1904
- zoj2970
- LeetCode 418. Sentence Screen Fitting
- 2017美国数学建模MCM A题(连续型)翻译 管理赞比西河
- 2017美国数学建模MCM B题(离散型)翻译 收费后合并
- 2017美国数学建模MCM C题(大数据)翻译 “合作和导航”
- Matlab编程与数据类型 -- 内联函数
- Python抓取CSV文件中数据【V2】
- JZOJ 3887. 【长郡NOIP2014模拟10.22】字符串查询
- 第64篇 摄像头屏蔽(四)及运行官网音频代码
- 2017.1.19【初中部 】普及组模拟赛C组 小x的游戏 题解