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:
- There should be at-least one space between each word.
- If a line has only one word, then it should be left justified.
Solution in C++
#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++) { 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; }
Output:
"This is an", "example of text", "justification. "
Bharath Prathivadi bayankaram
nice code its clear cut explanation