Created
October 24, 2013 12:27
-
-
Save zsh-89/7136289 to your computer and use it in GitHub Desktop.
Leetcode: Text Justification
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<string> fullJustify(vector<string> &words, int L) { | |
int N = words.size(); vector<string> ans; | |
for (int i = 0; i < N;) { | |
int n = 1; int len = words[i].size(); | |
for (int j = i+1; j < N; ++j) { | |
if (len + words[j].size() + 1 > L) break; | |
len += words[j].size() + 1; | |
++n; | |
} | |
if (i+n < N) { // not last line. | |
string line; | |
if (n > 1) { // at least two words | |
int sp = (L-len)/(n-1); | |
int ex_sp = (L-len)%(n-1); | |
string space(sp, ' '); | |
for (int k = i; k < i+n-1; ++k) { | |
line += words[k] + ' ' + space; | |
if (ex_sp) { | |
line += ' '; | |
--ex_sp; | |
} | |
} | |
line += words[i+n-1]; | |
} else if (n==1) { // one word | |
line += words[i]+string(L-len, ' '); | |
} | |
ans.push_back(line); | |
} else { // last line | |
int sp = L - len; string line; | |
for (int k = i; k < i+n-1; ++k) line += words[k] + ' '; | |
line += words[i+n-1] + string(sp, ' '); | |
ans.push_back(line); | |
} | |
i+=n; | |
} | |
return ans; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
因为一个typo : k < i+n-1打成了 i < i+n-1找了许久. 果然流程每一步均不可废.