即文本對齊:填充單詞之間空格使得佔滿一行(除了最後一行左對齊)。
如:words
: ["This", "is", "an", "example", "of", "text", "justification."]
,L
: 16
.
對齊後:app
"This is an" "example of text" "justification. "
預讀單詞,獲得每一行的單詞最大容納量,計算單詞間的空格數。設總字符串長度爲N
,時間複雜度爲O(N)
,空間複雜度爲O(N)
。spa
class Solution { public: vector<string> fullJustify(vector<string>& words, size_t maxWidth) { if (words.size() == 0U) return std::vector<std::string>(); std::vector<std::string> justify; justify.reserve(words.size()); for (size_t len = words.size(), i = 0U; 1;) { std::string lineStr(words[i]); lineStr.reserve(maxWidth); size_t left = words[i].size(), start = i; while (++i < len) { size_t next = words[i].size() + 1U; if (left + next > maxWidth) goto Justify; left += next; } for (; ++start < i; lineStr.append(words[start])) lineStr += ' '; lineStr.resize(maxWidth, ' '); justify.push_back(std::move(lineStr)); break; Justify: size_t gap = i - start - 1U; if (gap) { size_t extra = maxWidth - left, add = extra / gap + 2U, mod = start + extra % gap; for (; ++start <= mod; lineStr.append(words[start])) lineStr.append(add, ' '); for (--add; start < i; lineStr.append(words[start++])) lineStr.append(add, ' '); } else { lineStr.resize(maxWidth, ' '); } justify.push_back(std::move(lineStr)); } return std::move(justify); } };
主要應用了預讀的思想。code