Text 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 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.
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.

Solution: ...

 1 vector<string> res;
 2         int i = 0, N = words.size();
 3         while (i < N)
 4         {
 5             int length = words[i].size();
 6             int j = i + 1;
 7             while (j < N && length + words[j].size() + (j-i) <= L)
 8                 length += words[j++].size();
 9             // build line
10             string s(words[i]);
11             bool isLastLine = (j == N);
12             bool oneWord = (j == i + 1);
13             int average = isLastLine || oneWord ? 1 : (L - length) / (j - i - 1);
14             int extra = isLastLine || oneWord ? 0 : (L - length) % (j - i - 1);
15             for (int k = i + 1; k < j; ++k) {
16                 s.append(extra > 0 ? average + 1 : average, ' ');
17                 s.append(words[k]);
18                 extra--;
19             }
20             s.append(L - s.size(), ' ');
21             // push line
22             res.push_back(s);
23             i = j;
24         }
25         return res;

 

posted @ 2014-04-24 03:02  beehard  阅读(147)  评论(0编辑  收藏  举报