首页 > 代码库 > [LeetCode] Text Justification

[LeetCode] 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 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.

要考虑到各种特殊情况,以及怎样才能让空余出来的空格分布尽可能的平均。cnt用来记录当前行有多少个单词,len用来记录当前单词的长度和。注意处理完一行后要执行i--,要不然程序会跳过第pos行。a为每个间隙平均分配到的空格数,b为不能被整除而余下的空格数,将这b个分配给前b个间隙就行了。

 1 class Solution { 2 public: 3     vector<string> fullJustify(vector<string> &words, int L) { 4         vector<string> res; 5         string s; 6         int pos = 0, cnt = 0; 7         int len = 0; 8         int a, b, c; 9         for (int i = 0; i < words.size(); ++i) {10             if (len + words[i].length() + cnt <= L) {11                 ++cnt;12                 len += words[i].length();13             } else {14                 s += words[pos];15                 if (cnt == 1) {16                     c = L - len;17                     for (int k = 0; k < c; ++k)18                         s +=  ;19                 } else {20                     a = (L - len) / (cnt - 1);21                     b = (L - len) % (cnt - 1);22                     for (int j = 1; j < cnt; ++j) {23                         c = a;24                         if (j <= b) ++c;25                         for (int k = 0; k < c; ++k) 26                             s +=  ;27                         s += words[pos+j];28                     }29                 }30                 res.push_back(s);31                 s.clear();32                 pos = i--;33                 cnt = 0;34                 len = 0;35             }36         }37         s += words[pos];38         for (int j = 1; j < cnt; ++j) {39             s = s +   + words[pos + j];40         }41         c = L - len - cnt + 1;42         for (int k = 0; k < c; ++k) {43             s +=  ;44         }45         res.push_back(s);46         return res;47     }48 };

 

[LeetCode] Text Justification