基本思路——遍历整个单词数组,并执行以下步骤:
- 求本行的单词个数以及单词的长度和
- 求均匀空格数和额外空格数
- 均匀填充单词
- 如果未填满,在末尾补空格
代码如下:
// // Created by jt on 2020/9/25. // #include <vector> #include <string> using namespace std; class Solution { public: vector<string> fullJustify(vector<string> &words, int L) { vector<string> res; for (int start = 0, end; start < words.size(); start = end) { int width = 0, spaces = 1, extra = 0; // 定位本行的末尾单词(注意这里的end为末尾单词的后一个下标) for (end = start; end < words.size() && width + words[end].size() + (end-start) <= L; ++end) { width += words[end].size(); } // 求空格数和额外空格数 if (end - start != 1 && end != words.size()) { spaces = (L - width) / (end - start - 1); extra = (L - width) % (end - start - 1); } // 填充本行字符串 string line(words[start]); for (int i = start + 1; i < end; ++i) { line += string(spaces, ' '); if (extra-- > 0) line += " "; line += words[i]; } // 填充末尾空格 line += string(L-line.size(), ' '); res.push_back(line); } return res; } };