首页 > 代码库 > Text Justification

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.

思路: 首先,确定当前行能加入的最大词数;然后,将额外空格均匀地分配到每个间隔。

         假设额外空格为s,当前行的最大词数为n,则,每个间隔最少分配s/(n-1)+1,并且,前s%(n-1)个间隔,需要多分配一个空格。

 1 class Solution { 2 public: 3     vector<string> fullJustify( vector<string> &words, int L ) { 4         vector<string> lines; 5         size_t start = 0; 6         while( start != words.size() ) { 7             string line = words[start]; 8             size_t len = words[start].length(), end = start + 1; 9             while( end != words.size() && len+1+words[end].length() <= L ) { len += 1+words[end].length(); ++end; }10             int n = end - start, s = L - len, i = 1;11             if( n == 1 || end == words.size() ) {12                  // only one word in current line or current is last line, all spaces are assigned to its right.13                  for( ; i < n; ++i ) { line += string(" ") + words[start+i]; }14                  line += string( s,   );15             } else {16                 // more than two words are in current line, extra space should be assigned evenly.17                 for( ; i <= s%(n-1); ++i ) { line += string( s/(n-1)+2,   ) + words[start+i]; }18                 for( ; i < n; ++i ) { line += string( s/(n-1)+1,   ) + words[start+i]; }19             }20             lines.push_back( line );21             start = end;22         }23         return lines;24     }25 };

 

Text Justification