标签:
没有复杂的算法,纯粹的模拟题
先试探,计算出一行能放几个单词
然后计算出单词之间有几个空格,注意,如果空格总长度无法整除空格数,前面的空格长度通通+1
最后放单词、放空格,组成一行,加入结果中
对于最后一行要特殊处理
代码:
1 vector<string> fullJustify(vector<string> &words, int L) { 2 vector<string> text; 3 int n = words.size(); 4 5 int i = 0; 6 int j = 0; 7 8 while ((i = j) < n) { 9 int wordsLen = 0; 10 // 试探 11 while (j < n && wordsLen + words[j].length() + j - i <= L) { 12 wordsLen += words[j].length(); 13 j++; 14 } 15 // 特殊处理最后一行 16 if (j == n) { 17 string line = words[i]; 18 for (int k = i + 1; k < j; k++) 19 line += " " + words[k]; 20 line += string(L - wordsLen - (j - i - 1), ‘ ‘); 21 text.push_back(line); 22 break; 23 } 24 25 if (j == i + 1) // 只有一个单词的行也单独处理,避免除0 26 text.push_back(words[j - 1] + string(L - words[j - 1].length(), ‘ ‘)); 27 else { // 普通情况 28 int padLen = (L - wordsLen) / (j - i - 1); 29 int remainNum = L - wordsLen - padLen * (j - i - 1); 30 string line = words[i]; 31 for (int k = i + 1; k < j; k++) { 32 string pad(padLen, ‘ ‘); 33 if (remainNum > 0) { 34 pad += " "; 35 remainNum--; 36 } 37 line += pad + words[k]; 38 } 39 text.push_back(line); 40 } 41 } 42 43 return text; 44 }
Leetcode#68 Text Justification
标签:
原文地址:http://www.cnblogs.com/boring09/p/4243875.html