O(n) time
要确认一下单词长度是否会超过limit
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Solution { public: vector<string> fullJustify(vector<string>& words, int maxWidth) { vector<string> res; for (int i = 0, n = words.size(); i < n;) { int cnt = 0, len = 0; while (i + cnt < n && len + words[i + cnt].length() + cnt <= maxWidth) { len += words[i + cnt].length(); ++cnt; } string line = words[i]; for (int j = 1; j < cnt; ++j) { if (i + cnt >= n) { line += " "; } else { line.append((maxWidth - len) / (cnt - 1) + (j <= (maxWidth - len) % (cnt - 1)), ' '); } line += words[i + j]; } line.append(maxWidth - line.length(), ' '); res.push_back(line); i += cnt; } return res; } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| class Solution { public: vector<string> fullJustify(vector<string>& words, int maxWidth) { int n = words.size(), cnt = -1; vector<int> indices; vector<string> res; for (int i = 0; i < n; ++i) { if (cnt + 1 + words[i].length() <= maxWidth) { cnt += 1 + words[i].length(); indices.push_back(i); } else { stack<int> spaces; int slots = indices.size() - 1, total = maxWidth - cnt + slots; string s = words[indices[0]]; if (slots == 0) { s.append(total, ' '); } else { while (total > 0) { int space = total / slots--; spaces.push(space); total -= space; } for (int j = 1; j < indices.size(); ++j) { s.append(spaces.top(), ' ').append(words[indices[j]]); spaces.pop(); } } res.push_back(s); cnt = words[i].length(); indices = {i}; } if (i == n - 1) { string s = words[indices[0]]; for (int j = 1; j < indices.size(); ++j) { s += " " + words[indices[j]]; } s += string(maxWidth - s.length(), ' '); res.push_back(s); } } return res; } };
|