Advertisement
thewitchking

Untitled

Dec 14th, 2023
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.82 KB | None | 0 0
  1. class Solution {
  2.     int MAX_WIDTH;
  3.     public List<String> fullJustify(String[] words, int maxWidth) {
  4.         List<String> res = new ArrayList<>();
  5.         int i = 0;
  6.         int n = words.length;
  7.         MAX_WIDTH = maxWidth;
  8.         while(i < n){
  9.             int lettersCount = words[i].length();
  10.             int spaceCount = 0;
  11.             int j = i+1;
  12.             while(j<n && lettersCount+spaceCount+words[j].length()+1<=maxWidth){
  13.                 lettersCount+= words[j].length();
  14.                 spaceCount+= 1;
  15.                 j++;
  16.             }
  17.             int remainingSpaces = maxWidth - lettersCount;
  18.             int numSlots = spaceCount == 0 ? 0 : remainingSpaces / spaceCount;
  19.             int extraSpaces = spaceCount == 0 ? 0 : remainingSpaces % spaceCount;
  20.             if(j == n){
  21.                 //last line must be left justified
  22.                 numSlots = 1;
  23.                 extraSpaces = 0;
  24.             }
  25.             String toBeAdded = findLine(words, i, j, numSlots, extraSpaces);
  26.             res.add(toBeAdded);
  27.             i=j;
  28.  
  29.         }
  30.         return res;
  31.     }
  32.  
  33.         String findLine(String[] words, int i, int j, int numSlots, int extraSpaces){
  34.             StringBuilder line = new StringBuilder();
  35.             for(int k=i ;k<j; k++){
  36.                 line.append(words[k]);
  37.                 if(k == j-1){
  38.                     //last word of line
  39.                     continue;
  40.                 }
  41.                 for(int l=1;l<=numSlots;l++){
  42.                     line.append(" ");
  43.                 }
  44.                 if(extraSpaces > 0){
  45.                     line.append(" ");
  46.                     extraSpaces--;
  47.                 }
  48.             }
  49.             while(line.length() < MAX_WIDTH){
  50.                 line.append(" ");
  51.             }
  52.             return line.toString();
  53.         }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement