leetcode Text justification

来源:互联网 发布:sql错误信息注入 编辑:程序博客网 时间:2024/06/03 19:25


没有难度,纯粹是看考虑情况是不是足够。代码看起来比较繁杂。

class Solution {public:    void justifyStr(string &s, int L){int n = L - s.length();if (n == 0){return;}int m = 0, i = 0;while (i < s.length()){while (i < s.length() && s[i] != ' ')i++;while (i < s.length() && s[i] == ' ')i++;m++;}m--;if (m <= 0)//one word a line{i = 0;while (i < n){s = s + " ";i++;}return;}int d = n / m;//average spaceint q = 0;//left spaceif (d == 0){q = n;}else{q = d == 1 ? n % m : n % d;}i = 0;string blank = "";while (i < d){blank += " "; i++;}i = 0;while (i < s.length() && m > 0){while (i < s.length() && s[i] != ' ')i++;while (i < s.length() && s[i] == ' ')i++;if (q > 0){s = s.substr(0, i) + blank + " " + s.substr(i);i += d + 1;q--;}else{s = s.substr(0, i) + blank + s.substr(i);i += d;}m--;}}vector<string> fullJustify(vector<string> &words, int L) {if (words.size() < 1){return words;}vector<string> res;string currs = "", currw = words.front();string flag = "";int index = 1, n = words.size(), itmp;while (index < n){if (currw.length() > L){if (currs != ""){justifyStr(currs, L);res.push_back(currs);}res.push_back(currw.substr(0, L));currw = currw.substr(L);currs = "";flag = "";continue;}itmp = currs.length() + flag.length() + currw.length();if (itmp == L){currs = currs + flag + currw;res.push_back(currs);currs = "";flag = "";currw = words[index++];}else if (itmp < L){currs = currs + flag + currw;flag = " ";currw = words[index++];}else{justifyStr(currs, L);res.push_back(currs);currs = "";flag = "";}}//last lineitmp = currs.length() + flag.length() + currw.length();if (itmp <= L){currs = currs + flag + currw;if (itmp < L){string blank = "";int i = 0;while (i < L - itmp){blank += " ";i++;}currs += blank;}res.push_back(currs);}else{justifyStr(currs, L);res.push_back(currs);justifyStr(currw, L);res.push_back(currw);}return res;}};


0 0
原创粉丝点击