Leetcode Text Justification Problem Solution

In this 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.

Leetcode Text Justification Problem Solution


Problem solution in Python.

class Solution:
    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
        res = []
        start = 0
        n = len(words)
        while start < n:
            new_line = ''
            temp = []
            potential = 0
        
            for i in range(start, n):
                if len(words[i]) + 1 <= maxWidth - potential:
                    potential += len(words[i]) + 1
                    temp.append(words[i])
                    start = i + 1
                    if i == n - 1:
                        new_line = ' '.join(temp)
                        new_line +=  ' ' * (maxWidth - potential + 1)
                        break
                elif len(words[i]) == maxWidth - potential:
                    temp.append(words[i])
                    new_line = ' '.join(temp)
                    start = i + 1
                    if i == n - 1:
                        new_line = ' '.join(temp)
                    break
                else:
                    white_space = maxWidth - potential + len(temp)
                    if len(temp) == 1:
                        
                        new_line = temp[0] + ' ' * white_space
                    elif white_space % (len(temp) - 1) == 0:
                        new_line = (' ' * (white_space // (len(temp) - 1))).join(temp)
                    else:
                        remain = white_space % (len(temp) - 1)
                        left = (' ' * (white_space // (len(temp) - 1) + 1)).join(temp[:remain])
                        right = (' ' * (white_space // (len(temp) - 1))).join(temp[remain:])
                        new_line = left + ' ' * ((white_space // (len(temp) - 1)) + 1) + right
                    break
            res.append(new_line)
        return res

Problem solution in Java.

class Solution {
    public List<String> fullJustify(String[] words, int maxWidth) {
        List<String> res = new ArrayList();
        
        int curWidth = 0;
        List<String> line = new ArrayList();
        for (String s : words) {
            
            if (curWidth == 0) {
                curWidth += s.length();
                line.add(s);
                continue;
            } 
            
            // add Line
            if (curWidth + s.length() + 1 > maxWidth) {
                addLine(res, line, maxWidth);
                line = new ArrayList();
                line.add(s);
                curWidth = s.length();
            } else {
                curWidth += s.length() + 1;
                line.add(s);
            }
        }
        
        // process last line
        if (line.size() == 0) return res;
        
        if (line.size() == 1) 
            addOneWord(res, line.get(0), maxWidth);
        
        if (line.size() > 1) {
            StringBuilder build = new StringBuilder();
            build.append(line.get(0));
            for (int i = 1; i < line.size(); i++) {
                build.append(" ").append(line.get(i));
            }
            addSpace(build, maxWidth - build.toString().length());
            res.add(build.toString());
        }       
        
        return res;
    }
    
    private void addOneWord(List<String> res, String word, int maxWidth) {
        StringBuilder build = new StringBuilder();
        build.append(word);
        addSpace(build, maxWidth - word.length());
        res.add(build.toString());
        return;
    }
    
    private void addLine(List<String> res, List<String> line, int maxWidth) {
        StringBuilder build = new StringBuilder();
        if (line.size() == 1) {
            addOneWord(res, line.get(0), maxWidth);
            return;
        }
            
        int wordlen = 0;
        for (String s : line) {
            wordlen += s.length();
        }
        
        int emptySpace = maxWidth - wordlen;
        int extraSpace = emptySpace % (line.size()-1);
        int everySpace = emptySpace / (line.size()-1);
        
        for (int i = 0; i < line.size()-1; i++) {
            build.append(line.get(i));
            addSpace(build, everySpace);
            if (extraSpace-- > 0) 
                addSpace(build, 1);
            
        }
        if (line.size() > 1) build.append(line.get(line.size()-1));
        
        res.add(build.toString());
    }
    
    private void addSpace(StringBuilder build, int n) {
        for (int i = 0; i < n; i++) {
            build.append(" ");
        }
    }
}


Problem solution in C++.

class Solution
{
public:
vector fullJustify(vector& words, int maxWidth) {
vector vec;
   int i = 0;
    
    while(i<words.size())
    {
        int j = i+1;
        int sum = words[i].length();
        int curr = 0;
        while(j<words.size() and sum+words[j].size()+1+curr<=maxWidth)
        {
            sum += words[j].length();
            j++;
            curr++;
        }
        string now = "";
        int extra = (curr==0)?0:(maxWidth - sum)/curr;
        int more = (curr==0)?0:(maxWidth - sum)%curr;
        if(j==words.size())
        {
             for(int k=i;k<j;k++)
            {
                  now += words[k];
                 now += " ";
            }
            now.pop_back();
        }
        else
        {
             for(int k=i;k<j;k++)
            {
                now += words[k];
                if(k==j-1)
                    break;
                for(int g=0;g<extra;g++)
                {
                    now += " ";
                }
                if(more)
                {
                    now += " ";
                    more--;
                }
            }
        }
       
        cout<<now.length()<<" ";
        while(now.length()<maxWidth)
            now += " ";
        vec.push_back(now);
        i=j;
    }
    
    return vec;
}
 
};


Post a Comment

0 Comments