我的思路:
循环遍历输入的单词,每次获取一组符合<L要求的单词组合,然后填充。
代码参考别人的,由于最近比较急躁。
这道题最关键的问题是要清楚:
(1)空格要平均,且左边比右边多。注释2
(2)由于单词之间要有间隔,所以,在统计满足<L的单词组时,必须考虑空格,注释1
1 vector<string> fullJustify(vector<string> &words, int L) { 2 // Note: The Solution object is instantiated only once. 3 vector<string> res; 4 if(words.size() < 1){ 5 string tmp = ""; 6 res.push_back(tmp); 7 return res; 8 } 9 10 int pword = 0; 11 while(pword < words.size()) 12 { 13 int len = words[pword].size(); 14 int pbegin = pword; 15 while((pword + 1 < words.size()) && (len + pword - pbegin < L))//注释1,单词间必须要有一个空格 16 { 17 pword++; 18 len += words[pword].size(); 19 } 20 if(len + pword - pbegin > L) 21 { 22 len -= words[pword].size(); 23 pword--; 24 } 25 string tmp = ""; 26 if(pbegin == pword){ 27 tmp = words[pbegin]; 28 int spacenum = L-len; 29 while(spacenum--) 30 tmp += ‘ ‘; 31 }else{ 32 if(pword == words.size()-1) 33 { 34 while(pbegin < pword) 35 tmp += words[pbegin++] + ‘ ‘; 36 tmp += words[pbegin]; 37 if(tmp.size() < L) 38 { 39 int spacenum = L-tmp.size(); 40 while(spacenum--) 41 tmp += ‘ ‘; 42 } 43 }else{ 44 int samespace = (L - len)/(pword - pbegin); 45 int otherspace = (L - len)%(pword - pbegin); 46 while(pbegin < pword) 47 { 48 int spacenum = samespace; 49 if(otherspace>0) 50 { 51 otherspace--;//注释2:先平均填充,然后余下的平均分给前面的单词间 52 spacenum++; 53 } 54 tmp += words[pbegin++]; 55 while(spacenum--) 56 tmp += ‘ ‘; 57 } 58 tmp += words[pbegin]; 59 } 60 } 61 res.push_back(tmp); 62 pword++; 63 } 64 return res; 65 }
LeetCode--Text Justification,布布扣,bubuko.com
时间: 2024-10-13 23:56:36