Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' '
when necessary so that each line has exactly L characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left justified and no extra space is inserted between words.
For example,
words: ["This", "is", "an", "example", "of", "text", "justification."]
L: 16
.
Return the formatted lines as:
[ "This is an", "example of text", "justification. " ]
Note: Each word is guaranteed not to exceed L in length.
题目简述:给定单词组,和长度L,将单词组调整为每行长度都为L的文本,且左右对齐;最后一行左对齐!对于两个单词之间的空格,做到尽可能的相等,若无法均等,则需满足任意空格长度大于其右边的空格长度。如例子中的第二行,左边的空格长度为2,右边的为1。
Note:每一个单词的长度都不会超过L
思路:题目中有提到You should pack your words in a greedy approach,需要用到贪婪的方法
若一行中存在多个单词,则单词之间的空格长度至少为1。
因此,若单词1的长度+1(空格)+ 单词2的长度+1(空格)+...........+单词n的长度 <= L,则说明单词1,单词2,...............,单词n可以在同一行出现
若同时满足:单词1的长度+1(空格)+ 单词2的长度+1(空格)+...........+单词n的长度+1(空格)+ 单词n+1的长度 > L
则说明:单词1~单词n应该处于同一行。
然后,我们令C = L - 单词1的长度-1(空格)- 单词2的长度-1(空格)-...........-单词n的长度。
我们知道这一行一共存在n-1个空格,将长度C分配到这n-1个空格中,满足之前提到的空格长度的要求。
然后对特殊情况:
1、当一行仅存在一个单词时,如果需要用空格填充,则全部填充在单词的右边
2、当改行为最后一行时,单词之间的空格长度均为1,如果需要用空格填充,则全部填充在最后一个单词的右边。
以上,代码如下:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
int len = words.size();
vector<string> s;
int i = 0;
int count = 0;
while(i < len){
int start = i;
int w = 0;
count ++;
while(i < len && w + words[i].length() <= maxWidth){
w += words[i].length();
++w;
++i;
}
--w;
int c = maxWidth-w;
string str = "";
if(i-start == 1 || i == len){
for(int k = start; k < i-1; ++k){
str+=words[k];
str+=" ";
}
str+=words[i-1];
for(int k = 0; k < c; ++k){
str+=" ";
}
}
else{
int a = c/(i-start-1);
int b = c%(i-start-1);
for(int j = start; j < i-1; ++j){
str+=words[j];
str+=" ";
for(int k = 0; k < a; ++k){
str+=" ";
}
if(j-start < b){
str+=" ";
}
}
str+=words[i-1];
}
s.push_back(str);
}
return s;
}