Given a sentence and maxWidth. Arrange the text in such a way that each line has exactly maxWidth characters and is fully justified.

Your answer should be of greedy approach. You should pack as many words you can in each line. If you cannot fit the whole word, then fill the extra spaces with ‘ ‘ (empty space).

Extra spaces between words should be evenly distributed between the words.

Example:

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

This question can be divided into 2 different parts.
In the first part, we need to check how many words can be fit into a single line.
In the second part, determine the space to be inserted between those lines equally. To achieve this calculate the number of white spaces to be introduced and divide by the number of words.

Some of the corner cases to be considered:

1. There should be at-least one space between each word.
2. If a line has only one word, then it should be left justified.

/*
* File     : text_justification.cpp
*/

#include<iostream>
#include<vector>
#include<string>

using namespace std;

vector<string> text_justification(vector<string> &words, int maxWidth)
{

  vector<string> result;
  for(int i = 0, w; i < words.size(); i = w) 
  {
    //reset width to 0. This width is checked with maxWidth
    int width = 0;

    //check how many words will fit into the line
    for(w = i; w < words.size() && width + words[w].size() + w - i <= maxWidth; w++) 
    {
      cout<<"Inside 2nd for loop w = "<<w<<" i = "<<i<<" words[w] = "<<words[w]<<" ***width + words[w].size() + w - i  = "<<width + words[w].size() + w - i <<endl;
      width += words[w].size();
    }


    int space = 1, extra = 0;
    if(w - i != 1 && w != words.size()) 
    {
      space = (maxWidth - width) / (w - i - 1);
      extra = (maxWidth - width) % (w - i - 1);
    }

    string line(words[i]);
    for(int k = i + 1; k < w; k++) 
    {
      line += string(space, ' ');
      if(extra-- > 0) 
      {
        line += " ";
      }
      line += words[k];
    }

    line += string(maxWidth - line.size(), ' ');
    result.push_back(line);
  }
  return result;

}




int main()
{

  vector<string> words = {"This", "is", "an", "example", "of", "text", "justification."};
  int maxWidth = 16;

  vector<string> result = text_justification(words, maxWidth);

  for (const auto& value : result) 
  {
      cout << value << '\n';
  }

  return 0;
}
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *