In the Leetcode Text Justification problem solution 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.
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
Solution in C++ Programming
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> vec;
justified(words,maxWidth,vec);
return vec;
}
void justified(vector<string>& words, int maxWidth, vector<string>& vec){
if(words.size()==1){
string str = words[0];
words.erase(words.begin());
while(str.size()<maxWidth){
str = str + " ";
}
vec.push_back(str);
return;
}
string str_temp;
str_temp = words[0];
int width=str_temp.size();
int number_of_word=1;
int i = 1;
while(i<words.size() && width+words[i].size()+1<=maxWidth){
width=width+words[i].size()+1;
number_of_word++;
i++;
}
if(number_of_word==1){
while(str_temp.size()<maxWidth){
str_temp = str_temp +" ";
}
vec.push_back(str_temp);
words.erase(words.begin());
return justified(words, maxWidth, vec);
}
else if(number_of_word==words.size()){
words.erase(words.begin());
for(int m=1; m<number_of_word; m++){
str_temp=str_temp+" "+words[0];
words.erase(words.begin());
}
while(str_temp.size()<maxWidth){
str_temp = str_temp +" ";
}
vec.push_back(str_temp);
return;
}
else{
int space = (maxWidth-width)/(number_of_word-1)+1;
int left = (maxWidth-width)%(number_of_word-1);
words.erase(words.begin());
for(int j=1; j<number_of_word; j++){
if(j<=left){
for(int k=0;k<space+1; k++){
str_temp=str_temp+" ";
}
str_temp=str_temp+words[0];
words.erase(words.begin());
}
else{
for(int l=0;l<space; l++){
str_temp=str_temp+" ";
}
str_temp=str_temp+words[0];
words.erase(words.begin());
}
}
vec.push_back(str_temp);
return justified(words, maxWidth, vec);
}
}
};
Solution in Java Programming
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> ans = new ArrayList<>();
if (words==null | words.length==0) return ans;
List<String> line = new ArrayList<>();
line.add(words[0]); // add the first word into the first line
int lineSize = words[0].length(), spaces = maxWidth - words[0].length();
for (int w=1; w< words.length; w++) {
String word = words[w];
if ((lineSize + word.length() + 1) <= maxWidth) {
// one extra word needs at least one space
lineSize += (word.length() + 1);
spaces -= word.length();
line.add(word);
} else {
// the line is full
StringBuilder sb = new StringBuilder(line.get(0));
int n = line.size()-1;
if (n>0) { // more than one word in the line
int s = spaces/n, r = spaces % n;
for (int i=1; i<line.size(); i++) {
// distribute the spaces evently from left to right
for (int j=0; j<s+(r>0? 1: 0); j++) sb.append(" ");
if (r>0) r--;
sb.append(line.get(i));
}
} else { // only one word in the line, append spaces till the end of line
while(sb.length() < maxWidth) sb.append(" ");
}
ans.add(sb.toString());
line = new ArrayList<>();
line.add(word);
lineSize = word.length();
spaces = maxWidth - word.length();
}
}
if (!line.isEmpty()) {
StringBuilder sb = new StringBuilder(String.join(" ", line)); // one space between each word
while(sb.length() < maxWidth) sb.append(" "); //append spaces till the end of line
ans.add(sb.toString());
}
return ans;
}
}
Solution in Python Programming
class Solution(object):
def fullJustify(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
def helper(stack,tmp_length,maxWidth,):
if len(stack) == 1:
return stack[-1] + " "*(maxWidth-len(stack[-1]))
remain_len = maxWidth-tmp_length
tmp_res = ""
for i in range(len(stack)):
tmp_res += stack[i]
num_blank = len(stack)-1-i
if num_blank:
blank_length = remain_len/num_blank+1 if remain_len%num_blank!=0 else remain_len/num_blank
tmp_res += ' '*blank_length
remain_len -= blank_length
return tmp_res+' '*(maxWidth-len(tmp_res))
res = []
if not words:return " "*maxWidth
tmp_length = 0
tmp_stack = []
j = 0
while j <len(words):
word = words[j]
tmp_length += len(word)
tmp_stack.append(word)
if tmp_length >= maxWidth or j == len(words) - 1:
if len(tmp_stack) == 1:
res.append(tmp_stack[-1]+' '*(maxWidth-len(tmp_stack[-1])))
elif maxWidth-tmp_length < len(tmp_stack)-1:
while len(tmp_stack) > 1:
last_word = tmp_stack.pop()
j -= 1
tmp_length -= len(last_word)
if maxWidth-tmp_length >= len(tmp_stack)-1:break
res.append(helper(tmp_stack,tmp_length,maxWidth))
else:
res.append(helper(tmp_stack,tmp_length,maxWidth))
tmp_stack = []
tmp_length = 0
j += 1
last_array = res[-1].split()
tmp = ""
for i,word in enumerate(last_array):
tmp+=word
if i != len(last_array)-1:
tmp += ' '
tmp += ' '*(maxWidth-len(tmp))
res[-1] = tmp
return res
Solution in C# Programming
public class Solution {
public IList<string> FullJustify(string[] words, int maxWidth) {
var result = new List<string>();
int r = 0;
while (r < words.Length) {
int l = r;
int wordLen = words[l].Length;
int count = 1;
// Get how many words in current line
while (r + 1 < words.Length && wordLen + count + words[r + 1].Length <= maxWidth) {
r++;
wordLen += words[r].Length;
count++;
}
var sb = new StringBuilder();
if (count > 1) {
// Caculate spaces between words
// evenLen - ideal len when spaces can evenly distributed, edge case: 1 for last line
// remian - spaces need to be padded, edge case: 0 for last line
int spaceLen = maxWidth - wordLen;
int evenLen = r == words.Length - 1? 1 : spaceLen / (count - 1);
int remain = r == words.Length - 1? 0 : spaceLen - evenLen * (count - 1);
while (l < r) {
sb.Append(words[l]);
sb.Append(' ', evenLen);
if (remain > 0) {
sb.Append(' ');
remain--;
}
l++;
}
}
sb.Append(words[r]);
if (sb.Length < maxWidth) sb.Append(' ', maxWidth - sb.Length);
result.Add(sb.ToString());
r++;
}
return result;
}
}
Also read,