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.
描述起来啰里啰嗦一大堆,其实很简单。class Solution {
public:
vector<string> fullJustify(vector<string> &words, int L) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<string> ret;
int length=words.size();
int linecount=0;
int linechs=0;
vector<string> temp;
vector<int> spacedistr;
for(int i=0 ; i<length ; i++){
linecount+=words[i].size();
if(linecount>L){
for(int j=0 ; j<temp.size() ; j++)
linechs+=temp[j].size();
spacedistr=asevenlyaspossible(L-linechs,temp.size()-1);
string inner;
for(int k=0 ; k<temp.size() ; k++){
inner.append(temp[k]);
for(int m=0 ; k<temp.size()-1 && m<spacedistr[k] ; m++)
inner.push_back(' ');
if(spacedistr.size()==0){
for(int n=0 ; n<L-temp[0].size() ; n++)
inner.push_back(' ');
}
}
ret.push_back(inner);
temp.clear();
spacedistr.clear();
linechs=0,linecount=0;
i--;
continue;
}
temp.push_back(words[i]);
linecount++;
}
string last;
if(temp.size()!=0){
int i=0;
for(i=0 ; i<temp.size()-1 ; i++){
last.append(temp[i]);
last.push_back(' ');
}
last.append(temp[i]);
for(i=last.size() ; i<L ; i++)
last.push_back(' ');
}
ret.push_back(last);
return ret;
}
vector<int> asevenlyaspossible(int a , int b){
vector<int> ret;
if(b==0)
return ret;
int count=a/b;
int less=a-count*b;
for(int i=0 ; i<b ; i++){
if(i<less)
ret.push_back(count+1);
else
ret.push_back(count);
}
return ret;
}
};