首页 > 代码库 > LeetCode "Text Justification"
LeetCode "Text Justification"
Just take care of corner cases!
class Solution {public: vector<string> fullJustify(vector<string> &words, int L) { vector<string> ret; int startInx = 0; while (startInx < words.size()) { // Get word count a line int wcnt = 0, spcnt = 0; int i = 0; bool lastRm = false; for (i = startInx; i < words.size(); i++) { wcnt += words[i].length(); spcnt = i - startInx + wcnt; if (spcnt >= L) { lastRm = spcnt > L; break; } } if (!lastRm) // good luck { string line; for (int j = startInx; j <= i && j < words.size(); j++) { line += words[j]; if (j < i) line += ‘ ‘; } if (line.length() < L) // should only happen to last word { line.append(L - line.length(), ‘ ‘); } ret.push_back(line); } else // needs to chop last one { // Handle spaces spcnt -= words[i].length() + 1; int slotCnt = i - startInx - 1; int sp2fill = L - spcnt + slotCnt; vector<string> sp; if (slotCnt == 0) slotCnt = 1; sp.resize(slotCnt); for (int k = 0; k < sp2fill; k++) { sp[k % slotCnt] += ‘ ‘; } // Compose string line; for (int j = startInx; j < i; j++) { line += words[j]; if (j < i - 1 || (i - startInx) == 1) { line += sp[j - startInx]; } } ret.push_back(line); } startInx = lastRm ? i : i + 1; } return ret; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。