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.
click to show corner cases.
Corner Cases:
A line other than the last line might contain only one word. What should you do in this case?
In this case, that line should be left-justified.
根据问题描述,需要注意的点有:
- 1. 如何获得具有最多word的一行:
有效字符串的长度+间隔的个数 <= maxWidth
- 2. 计算单词之间的空格数:每行单词之间的空格数不等时,如何处理?
- 将平分后剩余的空格,从前往后,每个间隔补上一个空格
- 3. 只有一个单词
- 4. 最后一行要求:单词之间只有1个空格,但是在最后需要补全剩余空格
- 剩余空格数 = maxWidth - 已存在的间隔 - 有效单词的长度
class Solution {
public:
int len(string& word) {
return word.size();
}
vector<string> fullJustify(vector<string>& words, int maxWidth) {
int words_nums = words.size(); //字符串总数
vector<string> full_ustify_string;
string *line = new string[words_nums];
int k = 0; //new line index
int i = 0; //word index
while (i < words_nums) {
int words_len = 0; //每行单词的长度
int intervals = -1; //每行所需间隔
int begin = i; //每行起始index
//===统计每行最多容纳的word===
while (words_len + intervals + len(words[i]) + 1 <= maxWidth) {
words_len += len(words[i++]);
intervals++;
//最后一行,不插入多余空格
if(i == words_nums) {
while (begin < i) {
line[k] += (words[begin++]);
if (begin != i) { //单词之间只有一个空格
line[k] += " " ;
}
else {
// 插入剩余空格
int res_spaces = maxWidth-words_len-intervals;
while (res_spaces--)
line[k] += " " ;
}
}
k++;
goto return_result;
}
}
//===计算空格数===
int spaces = 0; //每隔间隔平均空格数
int diff = 0; //多余空格
if (intervals <= 0) {
spaces = (maxWidth-words_len);
} else {
spaces = (maxWidth-words_len) / intervals;
diff = maxWidth-words_len - spaces*intervals;
}
//===写入到新行===
while (begin < i) {
line[k] += (words[begin++]);
if (begin == i && intervals != 0)//最后一个word无空格
break;
for (int j = 0; j < spaces; j++)
line[k] += " ";
if (diff-- > 0) //补上不能均分的空格
line[k] += " ";
}
k++;
}
return_result:
vector<string> result(line, line+k);
return result;
}
};
原文地址:http://blog.csdn.net/quzhongxin/article/details/45505263