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.
class Solution {
public:
vector<string> fullJustify(vector<string> &words, int L) {
vector<string> res;
vector<string> cur;
const int n = words.size();
int count = -1;
int wordL = 0;
for (int i = 0; i < n; i++) {
if (count + words[i].size() + 1 > L) {
res.push_back(handle(cur, wordL, L));
count = -1;
wordL = 0;
cur.clear();
}
cur.push_back(words[i]);
count += 1 + words[i].size();
wordL += words[i].size();
}
res.push_back(handle_end(cur, count, L));
return res;
}
private:
string handle(vector<string> &word, int wordL, int L) {
string answer;
if (word.size() == 1) {
answer += word[0];
for (int i = 0; i < L - wordL; i++) {
answer += " ";
}
return answer;
}
int d = (L - wordL) / (word.size() - 1);
int r = (L - wordL) % (word.size() - 1);
answer = word[0];
for (int i = 1; i < word.size(); i++) {
for (int j = 0; j < d; j++) {
answer += " ";
}
if (r > 0) {
answer += " ";
r--;
}
answer += word[i];
}
return answer;
}
string handle_end(vector<string> &word, int count, int L) {
string answer;
answer = word[0];
for (int i = 1; i < word.size(); i++) {
answer += " " + word[i];
}
for (int i = 0; i < L - count; i++) {
answer += " ";
}
return answer;
}
};
本文介绍了一种用于文本格式化的算法,该算法能够确保每行文本恰好达到指定长度,并实现左对齐和右对齐的效果。文章详细解释了如何通过贪婪方式填充单词,并在必要时插入额外空格来平衡每行的间距。
341

被折叠的 条评论
为什么被折叠?



