68. Text Justification

Hard
也是太messy的一道题了, discussion里面有一个post还是蛮有意思的,讨论这道题的意义:What does this question aim to teach?

今日最佳:
it teaches you in the real world. Programmers are always been ask to deal with dirty works.

class Solution {
    public List<String> fullJustify(String[] words, int maxWidth) {
        List<String> res = new ArrayList<>();
        if (words == null || words.length == 0){
            return res;
        }
        int index = 0;
        while (index < words.length){ 
            int curtLen = words[index].length();
            int last = index + 1;
            while (last < words.length){
                if (1 + words[last].length() + curtLen > maxWidth){
                    break;
                }
                curtLen += 1 + words[last].length();
                last++;
            }
            StringBuilder line = new StringBuilder();
            line.append(words[index]);
            int numGap = last - 1 - index;
            //if words[j - 1] is the last word or number of word is one in the line, left justify
            if (last == words.length || numGap == 0){
                for (int i = index + 1; i < last; i++){
                    line.append(" ");
                    line.append(words[i]);
                }
                for (int i = line.length(); i < maxWidth; i++){
                    line.append(" ");
                }
            } else {
                //middle justify
                //spacesPerGap是 extra spaces between words,计算curtLen时已算word之间本身的一个空格
                int spacesPerGap = (maxWidth - curtLen) / numGap;
                int remainSpaces = (maxWidth - curtLen) % numGap;
                for (int i = index + 1; i < last; i++){
                    for (int k = spacesPerGap; k > 0; k--){
                        line.append(" ");
                    }
                    if (remainSpaces > 0){
                        line.append(" ");
                        remainSpaces--;
                    }
                    line.append(" ");
                    line.append(words[i]);
                }
            }
            res.add(line.toString());
            index = last;
        }
        return res;
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/17158d88d435
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞