Problem Description:http://oj.leetcode.com/problems/text-justification/
Note: Just be careful about boundary when implementing it.
class Solution {
public:
string genNormalLine(vector<string> &words, int L, int start, int end){
int word_count = end - start + ;
string line;
if(word_count == ){
line.append(words[start]);
line.append(L-line.size(), ' ');
}else{
int slot_num = word_count - ;
int words_size = ;
for(int i = start; i <= end; i++)
words_size += words[i].size(); int space_num = L - words_size;
int reminder = space_num % slot_num;
int quotient = space_num / slot_num;
line.append(words[start]);
for(int i = start + ; i <= end; i++) {
if(reminder > ){
line.append(quotient + , ' ');
reminder --;
} else {
line.append(quotient, ' ');
} line.append(words[i]);
}
} return line;
} vector<string> fullJustify(vector<string> &words, int L) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<string> formatted_lines;
if(words.size() == )
return formatted_lines;
for(int i = ; i < words.size();){
int length = ; int j = i;
for(; j < words.size(); j ++){
if( j == i)
length += words[j].size();
else
length += (+ words[j].size()); if(length > L)
break;
} //put words in a line
if(j == words.size()) {
//last line
string line;
line.append(words[i]);
for(int k = i + ; k < words.size(); k++){
line.push_back(' ');
line.append(words[k]);
}
if(line.size() < L){
line.append(L-line.size(), ' ');
} formatted_lines.push_back(line);
}else {
//normal line
formatted_lines.push_back(genNormalLine(words,L, i, j - ));
} //next start index
i = j;
} return formatted_lines;
}
};