[LeetCode] Text Justification

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution {
void insertLine(vector<string>& res, vector<string>& picked, int len, int maxWidth) {
len = len - picked.size();
int space = maxWidth - len;
if(picked.size() == 1) {
res.push_back(picked[0] + string(space, ' '));
return;
}

stringstream ss;
int eachSpace = space / (picked.size() - 1);
int extraSpace = space % (picked.size() - 1);
for(int j = 0; j < picked.size(); j++) {
ss<<picked[j];
if(j != picked.size() - 1) ss<<string(eachSpace, ' ');
if(extraSpace) {
ss<<' ';
extraSpace--;
}
}
res.push_back(ss.str());
}
void insertLastLine(vector<string>& res, vector<string>& picked, int len, int maxWidth) {
stringstream ss;
int space = maxWidth - len + 1;
for(int i = 0; i < picked.size(); i++) {
ss<<picked[i];
if(i != picked.size() - 1) ss<<' ';
}
ss<<string(space, ' ');
res.push_back(ss.str());
}
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> picked, res;
int len = 0;
for(int i = 0; i < words.size(); i++) {
if(len + words[i].size() > maxWidth) {
insertLine(res, picked, len, maxWidth);
picked.clear();
len = 0;
}
picked.push_back(words[i]);
len += words[i].length() + 1;
}

insertLastLine(res, picked, len, maxWidth);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/12/PS/LeetCode/text-justification/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.