leetcode 68 Text Justification

Lc68 Text Justification

我们首先要确定当前这一行能放下words[i]~words[?],

然后是如何分配空格,

如果是最后一行或是这一行只能放下一个单词,那么空格应该全部在右侧

否则,应该平均分配,余下的依次从左到右分配

 1 class Solution {
 2     public List<String> fullJustify(String[] words, int maxWidth) {
 3         int index = 0;
 4         List<String> res = new ArrayList<>();
 5         while(index < words.length){
 6             int last = index + 1;//index~last-1为这一行能放下的单词
 7             int count = words[index].length();
 8             while(last < words.length){
 9                 if(count + 1 + words[last].length() > maxWidth)
10                     break;
11                 count += words[last].length() + 1;
12                 last++;
13             }
14             
15             StringBuilder sb = new StringBuilder();
16             sb.append(words[index]);//先将index放入这一行
17             int lineWordsCnt = last - index - 1;//剩下未放单词的数量
18             if(lineWordsCnt == 0 || last == words.length){
19                 for(int i=index+1; i<last; i++){
20                     sb.append(" ").append(words[i]);
21                 }
22                 for(int i=count; i<maxWidth; i++){
23                     sb.append(" ");
24                 }
25             }else{
26                 int spaces = (maxWidth - count) / lineWordsCnt; //每个空挡都应该放的空格
27                 int plusSpaces = (maxWidth - count) % lineWordsCnt; //未除尽,余下的空格,依次从左到右填上
28                 
29                 for(int i=index+1; i<last; i++){
30                     for(int j=0; j<spaces; j++){
31                         sb.append(" ");
32                     }
33                     if(plusSpaces > 0){
34                         sb.append(" ");
35                         plusSpaces--;
36                     }
37                     sb.append(" ");
38                     sb.append(words[i]);
39                 }
40             }
41             res.add(sb.toString());
42             index = last;
43         }
44         return res;
45     }
46 }
原文地址:https://www.cnblogs.com/hwd9654/p/10982953.html