标签:leetcode 面试 justification 排版
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 exactlyL 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.
此代码在leetcode上实际运行时间为2ms。
基本思路为:
1, 按一个空格作为间隔的情况下,统计一行能装下的字数。
2, 不足L的话,平摊到每个间隔上。
下面代码中, spaces变量,表示,每个间隔的空格数
由于每个间隔的空格数,无法完全相等。
故用extra,表示将持有零头空格的间隔数。
末尾空格的补齐适用于最后一行。
class Solution { public: vector<string> fullJustify(vector<string> &words, int L) { vector<string> ans; int begin = 0; while (begin < words.size()) { int last = begin; int linesize = words[begin++].size(); while (begin < words.size() && linesize + 1 + words[begin].size() <= L) { linesize += 1 + words[begin].size(); begin++; } int spaces = 1, extra = 0; if (begin < words.size() && begin != last + 1) { spaces = (L - linesize) / (begin - last - 1) + 1; extra = (L - linesize) % (begin - last - 1); } ans.push_back(words[last++]); while (extra--) { ans.back().append(spaces+1, ' '); ans.back().append(words[last++]); } while (last < begin) { ans.back().append(spaces, ' '); ans.back().append(words[last++]); } ans.back().append(L-ans.back().size(), ' '); } return ans; } };
Text Justification -- leetcode
标签:leetcode 面试 justification 排版
原文地址:http://blog.csdn.net/elton_xiao/article/details/44922205