# [68\. Text Justification](https://leetcode.com/problems/text-justification/) :::spoiler Solution ```cpp= class Solution { public: vector<string> fullJustify(vector<string>& words, int maxWidth) { int n = words.size(); int start = 0; vector<string> res; while (start < n) { int last = start, totalChars = 0; while (last < n && totalChars + words[last].size() + last - start <= maxWidth) { totalChars += words[last++].size(); } string cur; int space = maxWidth - totalChars; for (int k = start; k < last; ++k) { cur += words[k]; if (space > 0) { int cnt; if (last == n) { if (last - k == 1) { cnt = space; } else { cnt = 1; } } else { if (last - k > 1) { if (space % (last - k - 1) == 0) { cnt = space / (last - k - 1); } else { cnt = space / (last - k - 1) + 1; } } else { cnt = space; } } cur.append(cnt, ' '); space -= cnt; } } res.push_back(cur); start = last; } return res; } }; ``` - T: $O(n \cdot k)$ - S: $O(m)$ :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up