力扣 题目68- 文本左右对齐

题目

题解

没有什么技巧 就是复杂 直接看代码吧

代码(来自评论区大佬)

 1 class Solution {
 2 public:
 3     vector<string> fullJustify(vector<string>& words, int maxWidth) {
 4      vector<string>res;
 5         for(int i=0;i<words.size();i++)
 6         {
 7             int j=i+1;
 8             int len=words[i].size();
 9             while(j<words.size() && len+1+words[j].size()<=maxWidth)
10                len+=1+words[j++].size();
11             string line;
12             if(j==words.size() || j==i+1)
13             {
14                 line+=words[i];
15                 for(int k=i+1;k<j;k++) line+=' '+words[k];
16                 while(line.size()<maxWidth) line+=' ';
17             }
18             else
19             {
20                 int cnt=j-i-1,r=maxWidth-len+cnt;
21                 line+=words[i];
22                 int k=0;
23                 while(k<r%cnt) line+=string(r/cnt+1,' ')+words[i+k+1],k++;
24                 while(k<cnt) line+=string(r/cnt,' ')+words[i+k+1],k++;
25             }
26             res.push_back(line);
27             i=j-1;
28         }
29         return res;
30         }
31 };
View Code

 

posted @ 2022-06-06 14:05  无聊的阿库娅  阅读(10)  评论(0编辑  收藏  举报