【LeetCode】 -- 68.Text Justification
题目大意:给定一个数组容器,里面存有很多string; 一个int maxWith。让你均匀安排每一行的字符串,能够尽可能的均匀。
解题思路:字符串+贪心。一开始想复杂了,总觉的题意描述的不是很清楚,其实放到实际的场景中去,无非就是想让前端字符串布局变得更加美观,而设计的字符串对其方式(分散对齐)(如果每一行只有一个字符串的话,那么左对齐)。
附上代码:
1 vector<string> fullJustify(vector<string>& words, int maxWidth) 2 { 3 vector<string> ans; 4 string rec = ""; 5 int lenLine = words[0].length(); 6 vector<int>wordId; 7 wordId.push_back(0); 8 for(int i = 1; i < words.size(); i ++){ 9 if(lenLine + words[i].length() + 1 <= maxWidth){ 10 lenLine += words[i].length() + 1; 11 wordId.push_back(i); 12 }else{ 13 rec = ""; 14 rec += words[wordId[0]]; 15 if(wordId.size() == 1){ 16 string spaces(maxWidth - rec.length(), ' '); 17 rec += spaces; 18 }else{ 19 int totalLenOfWords = 0; 20 for(int j = 0; j < wordId.size(); j ++){ 21 totalLenOfWords += words[wordId[j]].length(); 22 } 23 int averageLenOfSpace = 0, leftLenOfSpace = 0; 24 averageLenOfSpace = (maxWidth - totalLenOfWords) / (wordId.size() - 1); 25 leftLenOfSpace = maxWidth - totalLenOfWords - averageLenOfSpace * (wordId.size() - 1); 26 for(int j = 1; j < wordId.size(); j ++){ 27 string space(averageLenOfSpace, ' '); 28 rec += space; 29 if(leftLenOfSpace > 0){ 30 rec += " "; 31 leftLenOfSpace --; 32 } 33 rec += words[wordId[j]]; 34 } 35 } 36 ans.push_back(rec); 37 lenLine = words[i].length(); 38 wordId.clear(); 39 wordId.push_back(i); 40 } 41 } 42 if(wordId.size()){ 43 rec = ""; 44 rec += words[wordId[0]]; 45 for(int j = 1; j < wordId.size(); j ++){ 46 rec += " "; 47 rec += words[wordId[j]]; 48 } 49 string spaces(maxWidth - rec.length(), ' '); 50 rec += spaces; 51 ans.push_back(rec); 52 } 53 return ans; 54 }
反思: 这道题的难点在于,要记得区分一种特殊状况:当该行只有一个word的时候。代码实现的速度还是比较慢,以后要速度解决这种没啥思维量的手速题。网易笔试告诉我:手速真的很重要。不要被外界因素干扰,心无旁骛的codeing。
最后:今天又看到了一个靠刷题算法逆袭成功的小硕,repeat my words: fuck all the leetcode problems and be a offer Harvester.