Easy to understand Java solution


  • 0
    R
    public class Solution {
        public List<String> fullJustify(String[] words, int maxWidth) {
            ArrayList<String> result = new ArrayList<String>();
            if(words.length == 0) return result;
            
            int start = 0, wordsLengthInCurLine = 0, wordsInCurLine = 0;
            
            for(int i = 0; i < words.length; i++) {
                wordsInCurLine++;
                
                // length for i-1 words + currentWordLen + numOfMinSpacesBetweenWords
                int lineLength = wordsLengthInCurLine + words[i].length() + (i-start);
                
                if(lineLength == maxWidth) {
                    result.add(createLine(words, start, i, i-start));
                    start = i+1;
                    wordsLengthInCurLine = 0;
                    wordsInCurLine = 0;
                }
                else if(lineLength > maxWidth) {
                    result.add(createLine(words, start, i-1, maxWidth-wordsLengthInCurLine));
                    start = i;
                    wordsLengthInCurLine = words[i].length();
                    wordsInCurLine = 1;
                }
                else {
                    wordsLengthInCurLine += words[i].length();
                }
            }
            
            if(wordsInCurLine > 0) {
                StringBuffer sb = new StringBuffer(createLine(words, start, words.length-1, words.length-1-start));
                for(int s = 0; s < maxWidth-wordsLengthInCurLine-(words.length-1-start); s++) {
                    sb.append(' ');
                }
                result.add(sb.toString());
            }
            
            return result;
        }
        
        String createLine(String[] words, int start, int end, int numSpaces) {
            StringBuffer line = new StringBuffer();
            int numOfWords = end - start + 1;
            
            for(int i = start; i < end; i++) {
                line.append(words[i]);
                numOfWords--;
                int spaceBetweenWords = (int)Math.ceil((double)numSpaces/numOfWords);
                for(int s = 0; s < spaceBetweenWords; s++) {
                    line.append(' ');
                }
                
                numSpaces -= spaceBetweenWords;
            }
            
            line.append(words[end]);
            for(int s = 0; s < numSpaces; s++) {
                line.append(' ');
            }
            
            return line.toString();
        }
    }

Log in to reply
 

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