This is actually not the LeetCode version answer. But I think this is more likely in real word.
The Code is copied from the EPI. I have no clue to solve this problem at the first sight.
#include <string>
#include <vector>
#include <iostream>
#include <cmath>
using namespace std;
/*
Example:
words = ["This", "is", "an", "example", "of", "text", "justification"]
L : 16
return
[
"This is an",
"example of text",
"justification. "
]
*/
string JoinALineWithSpace(vector<string>& words, int start, int end, int numSpaces) {
size_t num_words_curr_line = end - start + 1;
string line;
for(int i = start; i < end; ++i) {
line += words[i];
--num_words_curr_line;
size_t num_curr_space = ceil(static_cast<double>(numSpaces)/num_words_curr_line);
line.append(num_curr_space, ' ');
numSpaces -= num_curr_space;
}
line += words[end];
line.append(numSpaces, ' ');
return line;
}
vector<string> fullJustify(vector<string>& words, int maxWidth) {
int maxLen = 0;
for(int i = 0; i < words.size(); ++i) {
if(words[i].size() > maxLen) maxLen = words[i].size();
}
if(maxLen > maxWidth) return {};
vector<string> res;
int num_words_curr_line = 0;
int curr_line_length = 0;
int curr_line_start = 0;
for(int i = 0; i < words.size(); ++i) {
++num_words_curr_line;
size_t lookahead_line_length = curr_line_length + words[i].size() + (num_words_curr_line - 1);
if(lookahead_line_length == maxWidth) {
res.push_back(JoinALineWithSpace(words, curr_line_start, i, i - curr_line_start));
curr_line_start = i + 1;
curr_line_length = 0;
num_words_curr_line = 0;
} else if(lookahead_line_length > maxWidth) {
res.push_back(JoinALineWithSpace(words, curr_line_start, i - 1, maxWidth - curr_line_start));
curr_line_start = i;
curr_line_length = words[i].size();
num_words_curr_line = 1;
} else {
curr_line_length += words[i].size();
}
}
if(num_words_curr_line > 0) {
string line = JoinALineWithSpace(words, curr_line_start, words.size() - 1, num_words_curr_line - 1);
line.append(maxWidth - curr_line_length - (num_words_curr_line - 1), ' ');
res.push_back(line);
}
return res;
}
int main(void) {
vector<string> words{"This", "is", "an", "example", "of", "text", "justification"};
vector<string> res = fullJustify(words, 16);
for(int i = 0; i < res.size(); ++i) cout << res[i] << endl;
}