Algorithm


Problem Name: 68. Text Justification

Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

For the last line of text, it should be left-justified, and no extra space is inserted between words.

Note:

  • A word is defined as a character sequence consisting of non-space characters only.
  • Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.
  • The input array words contains at least one word.

Example 1:

Input: words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16
Output:
[
   "This    is    an",
   "example  of text",
   "justification.  "
]

Example 2:

Input: words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16
Output:
[
  "What   must   be",
  "acknowledgment  ",
  "shall be        "
]
Explanation: Note that the last line is "shall be    " instead of "shall     be", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.

Example 3:

Input: words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20
Output:
[
  "Science  is  what we",
  "understand      well",
  "enough to explain to",
  "a  computer.  Art is",
  "everything  else  we",
  "do                  "
]

Constraints:

  • 1 <= words.length <= 300
  • 1 <= words[i].length <= 20
  • words[i] consists of only English letters and symbols.
  • 1 <= maxWidth <= 100
  • words[i].length <= maxWidth

Code Examples

#1 Code Example with C Programming

Code - C Programming


char *make_str1(char **words, int *lens, int x, int l, int width) {
   char *s;
   int i, j, k, num_of_space, rem_of_space;
   
   s = malloc((width + 1) * sizeof(char));
   //assert(s);
   
   if (x > 1) {
      num_of_space = (width - l) / (x - 1);
      rem_of_space = (width - l) % (x - 1);
   } else {
      num_of_space = width - l;
      rem_of_space = 0;
   }
   
   k = 0;
   for (i = 0; i  <  x; i ++) {
      strcpy(&s[k], words[i]);
      k += lens[i];
      for (j = 0; (i == 0 || i != x - 1) && j  <  num_of_space; j ++) {
         s[k] = ' ';
         k ++;
      }
      if (rem_of_space) {
         s[k] = ' ';
         k ++;
         rem_of_space --;
      }
   }
   s[k] = 0;
   
   return s;
}
char *make_str2(char **words, int *lens, int x, int l, int width) {
   char *s;
   int i, k;
   
   s = malloc(width * sizeof(char));
   //assert(s);
   
   k = 0;
   for (i = 0; i  <  x; i ++) {
      if (i) {
         s[k] = ' ';
         k ++;
      }
      strcpy(&s[k], words[i]);
      k += lens[i];
   }
   
   while (k  <  width) {
      s[k] = ' ';
      k ++;
   }
   s[k] = 0;
   
   return s;
}
char** fullJustify(char** words, int wordsSize, int maxWidth, int* returnSize) {
   int *lens, sz, n, i, l, k;
   char **p = NULL, *s;
   int a, b;
   
   sz = 10;
   n = 0;
   p = malloc(sz * sizeof(char *));
   lens = malloc(wordsSize * sizeof(int));
   //assert(p && lens);
   
   k = 0; a = 0;
   for (i = 0; i  <  wordsSize; i ++) {
      l = strlen(words[i]);
      //assert(l  < = maxWidth);
      lens[i] = l;
      if (k + l + i - a > maxWidth) {
         // form a line
         s = make_str1(&words[a], &lens[a], i - a, k, maxWidth);
         //printf("%s\n", s);
         //free(s);
         if (n == sz) {
            sz *= 2;
            p = realloc(p, sz * sizeof(char *));
            //assert(p);
         }
         p[n ++] = s;
         k = 0; a = i;
      }
      k += l;
   }
   
   s = make_str2(&words[a], &lens[a], i - a, k, maxWidth);
   //printf("%s\n", s);
   //free(s);
   if (n == sz) {
      sz *= 2;
      p = realloc(p, sz * sizeof(char *));
      //assert(p);
   }
   p[n ++] = s;
   
   *returnSize = n;
   
   free(lens);
   
   return p;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16

Output

x
+
cmd
[ "What must be", "acknowledgment ", "shall be " ]

#2 Code Example with C++ Programming

Code - C++ Programming


class Solution {
public:
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
        vector<string>res;
        if(maxWidth == 0) return {""};
        int i = 0, j = 0;
        while(j != words.size()){
            int len = -1;
            while(j < words.size() && len + words[j].size() + 1  < = maxWidth)
                len += words[j++].size() + 1;
            int space = maxWidth - len + j - i - 1;
            int k = i;
            while(space){
                words[k++] += " ";
                space--;
                if(j != words.size() && (k == j - 1 || k == j)) k = i;
                if(j == words.size() && k == j) k = j - 1;
            }
            string line = "";
            for(int l = i; l  <  j; l++)
                line += words[l];
            res.push_back(line>;
            i = j;
        }
        return res;
    }
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16

Output

x
+
cmd
[ "This is an", "example of text", "justification. " ]

#3 Code Example with Java Programming

Code - Java Programming


class Solution {
    public List fullJustify(String[] words, int maxWidth) {
        List list = new ArrayList<>();
        int idx = 0;
        int n = words.length;

        while (idx  <  n) {
            int count = 0;
            int currLength = 0;
            int oldIdx = idx;
            int totalWordLength = 0;

            while (idx  <  n && currLength + words[idx].length() <= maxWidth) {
                count++;
                currLength += words[idx].length() + 1;
                totalWordLength += words[idx].length();
                idx++;
            }

            StringBuilder sb = new StringBuilder();
            // Left Justify
            if (count == 1 || idx == n) {
                while (oldIdx  <  idx) {
                    sb.append(words[oldIdx++]);
                    if (!words[oldIdx-1].endsWith(".") && oldIdx != idx) {
                        sb.append(" ");
                    }
                }

                while (sb.length()  <  maxWidth) {
                    sb.append(" ");
                }
            }
            // Left & Right Justify
            else {
                int spacing = (maxWidth - totalWordLength) / (count - 1);
                int extraSpacing = maxWidth - totalWordLength - spacing * (count - 1);
                int tempIdx = oldIdx;
                while (tempIdx  <  idx) {
                    sb.append(words[tempIdx++]);
                    if (tempIdx != idx) {
                        int totalSpace = spacing + (extraSpacing > 0 ? 1 : 0);
                        extraSpacing--;
                        for (int j = 0; j  <  totalSpace; j++) {
                            sb.append(" ");
                        }
                    }
                }
            }

            list.add(sb.toString());
        }

        return list;
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16

Output

x
+
cmd
[ "This is an", "example of text", "justification. " ]

#4 Code Example with Javascript Programming

Code - Javascript Programming


const fullJustify = function(words, maxWidth) {
  const res = []
  let curRow = []
  let numOfChars = 0
  
  for (let w of words) {
    if (numOfChars + w.length + curRow.length > maxWidth) {
      for(let i = 0; i  <  maxWidth - numOfChars; i++) {
        if(curRow.length === 1) {
          curRow[0] += ' '
        } else {
          curRow[i % (curRow.length - 1)] += ' '
        }
      }
      res.push(curRow.join(''))
      curRow = []
      numOfChars = 0
    }
    curRow.push(w)
    numOfChars += w.length
  }

  const numOfSpace = maxWidth - numOfChars - (curRow.length - 1)
  let tail = ''
  for(let i = 0; i < numOfSpace; i++) tail += ' '
  res.push(curRow.join(' ') + tail>

  return res
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16

Output

x
+
cmd
[ "This is an", "example of text", "justification. " ]

#5 Code Example with Python Programming

Code - Python Programming


class Solution:
    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
        res, used, s = [], 0, []
        for i, w in enumerate(words):
            if not s or len(w) + used + len(s) <= maxWidth:
                used += len(w)
                s += [w]
            else:
                if len(s) == 1:
                    res.append(s[0] + (maxWidth - used) * ' ')
                else:
                    br = (maxWidth - used) // (len(s) - 1)
                    res.append(''.join((br + (i <= (maxWidth - used) % (len(s) - 1))) * ' ' + c for i, c in enumerate(s)).lstrip())
                used, s = len(w), [w]
        return res + [' '.join(c for c in s) + (maxWidth - used - len(s) + 1) * ' ']
Copy The Code & Try With Live Editor

Input

x
+
cmd
words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16

Output

x
+
cmd
[ "What must be", "acknowledgment ", "shall be " ]

#6 Code Example with C# Programming

Code - C# Programming


using System.Collections.Generic;
using System.Text;

namespace LeetCode
{
    public class _068_TextJustification
    {
        public IList < string> FullJustify(string[] words, int maxWidth)
        {
            var result = new List();

            int start = 0, len = 0;
            var builder = new StringBuilder();
            for (int i = 0; i  <  words.Length; i++)
            {
                if (len + words[i].Length > maxWidth)
                {
                    var space = maxWidth - len + (i - start);
                    builder.Clear();
                    for (int j = start; j  <  i; j++)
                    {
                        builder.Append(words[j]);

                        var tempSpace = j != i - 1
                            ? space / (i - start - 1) + ((j - start  <  (space % (i - start - 1))) ? 1 : 0)
                            : maxWidth - builder.Length;
                        builder.Append(new string(' ', tempSpace));
                    }
                    result.Add(builder.ToString());

                    len = 0;
                    start = i;
                }

                len += words[i].Length + 1;
            }

            builder.Clear();
            for (int j = start; j  <  words.Length; j++)
            {
                builder.Append(words[j]);
                var tempSpace = j != words.Length - 1
                    ? 1
                    : maxWidth - builder.Length;
                builder.Append(new string(' ', tempSpace));
            }
            result.Add(builder.ToString());

            return result;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16

Output

x
+
cmd
[ "What must be", "acknowledgment ", "shall be " ]
Advertisements

Demonstration


Previous
#67 Leetcode Add Binary Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
CodeChef solution FLOW010 - ID and Ship Codechef solution in C,C++