思路:
贪心。时间复杂度O(N),空间复杂度O(1)。
class Solution {
private:
/**
add space to a target line
@param s : target line
@param i : current space's number
@param n : interspace sum
@param L : space sum
@param is_last : whether is the last line
@return
*/
void addSpaces(string &s, int i, int n, int L, bool is_last) {
if(n < 1 || i > n - 1) return;
int spaces = is_last ? 1 : (L/n + (i < (L%n) ? 1 : 0));
s.append(spaces, ' ');
}
/**
connect words[begin, end] to a line
@param words
@param begin
@param end
@param len : the length of words[begin, end]
@param maxWidth
@param is_last : whether if is the last line
@return the connected line
*/
string connect(vector<string> &words, int begin, int end, int len, int maxWidth, bool is_last) {
string s;
int n = end - begin + 1;// words number
for(int i = 0; i < n; ++i) {
s += words[begin + i];
addSpaces(s, i, n - 1, maxWidth - len, is_last);
}
if(s.size() < maxWidth) {
s.append(maxWidth - s.size(), ' ');
}
return s;
}
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> res;
const int n = words.size();
int begin = 0, len = 0;//current line's starting point, current line's length
for(int i = 0; i < n; ++i) {
if(len + words[i].size() + (i - begin) > maxWidth) {
res.push_back(connect(words, begin, i-1, len, maxWidth, false));
begin = i;
len = 0;
}
len += words[i].size();
}
res.push_back(connect(words, begin, n-1, len, maxWidth, true));
return res;
}
};