标签:algorithm leetcode 面试题 二叉树 string
For example,
words: ["This", "is", "an", "example", "of", "text",
"justification."]
L: 16
.
Return the formatted lines as:
[ "This is an", "example of text", "justification. " ]
Note: Each word is guaranteed not to exceed L in length.
vector<string> fullJustify(vector<string> &words, int L) { vector<string> re; const int spaces = 1; int wordsNum = words.size(); if(L == 0) return words; string line; int iword = 0; while (iword < wordsNum) { int i = iword; int cur_len = 0; //append word.each word divided by one space. while(i < wordsNum && cur_len + words[i].size() + spaces <= L + 1) { cur_len += words[i++].size() + spaces; } //L too small. if(cur_len == 0) return re; //last line of the text. if(i == wordsNum){ line += words[iword]; for (int k = iword + 1; k < i; ++k) { line.append(1, ' '); line += words[k]; } line.append(L - line.size(), ' '); } else{ int wordsLen = cur_len - (i - iword); int fillSpaces = L - wordsLen; //just one word in this line. if(i - iword == 1) { line += words[iword]; line.append(fillSpaces, ' '); } // else { int eqSpaces = fillSpaces / (i - iword - 1); int remainSpaces = fillSpaces % (i - iword - 1); for (int ifill = 0; ifill < i - iword - 1; ++ifill) { //eg:abcd, L = 8, eqSpaces = 8/6 = 1, remainder = 2 // index 0 1 2 3 // a b c d , //a__b__c_d line += words[iword + ifill]; line.append(eqSpaces, ' '); if(--remainSpaces >= 0) line.append(1, ' '); } //last word in this line. line += words[i - 1]; } } iword = i; re.push_back(line); line.clear(); } return re; }
【leetcode】 Text Justification,布布扣,bubuko.com
标签:algorithm leetcode 面试题 二叉树 string
原文地址:http://blog.csdn.net/shiquxinkong/article/details/27836951