Share my LONG JAVA solution


  • 0
    W

    Get words for each line, and then create each line:

        public List<String> fullJustify(String[] words, int maxWidth) {
            List<String> res = new ArrayList<>();
            Queue<String> allWords = new LinkedList<>();
            for (String s : words) allWords.offer(s);
            
            Queue<String> wordsInLine = getWordsInLine(allWords, maxWidth);
            while (wordsInLine.size() > 0) {
                res.add(getLine(wordsInLine, maxWidth, allWords.isEmpty()));
                wordsInLine = getWordsInLine(allWords, maxWidth);
            }
            return res;
        }
    

    Fill end with spaces:

        private String fillEnd(String s, int maxWidth) {
            int diff = maxWidth - s.length();
            while (diff-- > 0) {
                s += " ";
            }
            return s;
        }
    

    Create the line with a list of words belong to this line:

        private String getLine(Queue<String> queue, int maxWidth, boolean isLastLine) {
            if (queue.size() == 1) {
                return fillEnd(queue.poll(), maxWidth);
            }
            
            StringBuilder sb = new StringBuilder();
            sb.append(queue.poll());
            if (isLastLine) {
                while (!queue.isEmpty()) {
                    sb.append(" ");
                    sb.append(queue.poll());
                }
                return fillEnd(sb.toString(), maxWidth);
            }
            
            int length = sb.length();
            for (String s : queue) length += s.length();
            int spaces = maxWidth - length;
            int buckets = queue.size();
            int extra = spaces % buckets;
            int avg = spaces / buckets;
            while (buckets-- > 0) {
                int num = extra-- > 0 ? avg + 1 : avg;
                for (int i = 0; i < num; i++) {
                    sb.append(" ");
                }
                sb.append(queue.poll());
            }
            return sb.toString();
        }
    

    Get a list of words that belong to a single line:

        private Queue<String> getWordsInLine(Queue<String> queue, int maxWidth) {
            Queue<String> res = new LinkedList<>();
            if (queue.isEmpty()) return res;
            
            int length = queue.peek().length();
            res.offer(queue.poll());
            while (!queue.isEmpty() && length + queue.peek().length() + 1 <= maxWidth) {
                length += queue.peek().length() + 1;
                res.offer(queue.poll());
            }
            return res;
        }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.