## Tuesday, November 25, 2014

### [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.
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.

1. 首先要能判断多少个word组成一行：

2. 知道一行的所有n个words，以及总长curLen之后要决定空格分配：

k = (21 - 14) / (4-1) = 2
m = (21 - 14) % (4-1)  = 1
A---B--C--D

3. 特殊情况：
(a) 最后一行：当读入到第i = words.size()-1 个word时为最后一行。该行k = 1，m = 0
(b) 一行只有一个word：此时n-1 = 0，计算(L - curLen)/(n-1)会出错。该行k = L-curLen, m = 0
(c) 当word[i].size() == L时。

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55``` ```class Solution { public: vector fullJustify(vector &words, int L) { int start = 0, end = -1, totLen = 0; bool isLast = false; vector ret; int i=0; while(iL) return ret; int newLen = totLen + (end-start+1) + words[i].size(); if(newLen<=L) { // words[i] can be in current line end = i; totLen += words[i].size(); i++; } else { // word[i-1] is the end of a line string line = createLine(words, L, start, end, totLen, false); ret.push_back(line); start = i; end = i-1; totLen = 0; } } string lastLine = createLine(words, L, start, end, totLen, true); ret.push_back(lastLine); return ret; } string createLine(vector &words, int L, int start, int end, int totLen, bool isLast) { string ret; if(start<0 || end>=words.size() || start>end) return ret; ret.append(words[start]); int n = end-start+1; // special case: one word or last line - left justified if(n==1 || isLast) { for(int i=start+1; i<=end; i++) ret.append(" " + words[i]); int j = L-totLen-(n-1); ret.append(j, ' '); return ret; } // normal case: fully justified int k = (L-totLen)/(n-1), m = (L-totLen)%(n-1); for(int i=start+1; i<=end; i++) { int nspace = i-start<=m ? k+1 : k; ret.append(nspace,' '); ret.append(words[i]); } return ret; } }; ```