LeetCode 68 - Text Justification

Given an array of words and a length L, format the text such that each line has exactly L 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 Lcharacters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do 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.

For example,
words: ["This", "is", "an", "example", "of", "text", "justification."]
L: 16.

Return the formatted lines as:

[
   "This    is    an",
   "example  of text",
   "justification.  "
]

Note: Each word is guaranteed not to exceed L in length.

Corner Cases:
  • A line other than the last line might contain only one word. What should you do in this case?
    In this case, that line should be left-justified.
public List<String> fullJustify(String[] words, int L) {
    List<String> result = new ArrayList<>();
    char[] sp = new char[L];
    Arrays.fill(sp, ' ');
    String spaces = new String(sp);
    int i = 0, n = words.length;
    while(i < n) {
        int j = i;
        int wordLen = 0, wordCnt = 0;
        while(i < n && words[i].length()+wordLen+wordCnt <= L) {
            wordLen += words[i].length();
            wordCnt++;
            i++;
        }
        StringBuilder sb = new StringBuilder();
        int spaceCnt = L - wordLen; // 空格总个数
        //只有一个word或者是最后一行的时候,需要左对齐
        boolean leftAlign = (wordCnt == 1 || i == n);
        int avgSp = leftAlign ? 1 : spaceCnt / (wordCnt - 1); //平均空格个数
        int remSp = leftAlign ? 0 : spaceCnt % (wordCnt - 1); //平均之后多出来的空格个数
        for(int k=0; k<wordCnt; k++) {
            sb.append(words[j+k]);
            if(k == wordCnt-1) break;
            int spLen = avgSp;
            if(remSp > 0) {
                remSp--;
                spLen++;
            }
            sb.append(spaces.substring(0, spLen));
        }
        if(sb.length() < L) {
            sb.append(spaces.substring(0, L-sb.length()));
        }
        result.add(sb.toString());
    }
    return result;
}

  

你可能感兴趣的:(LeetCode 68 - Text Justification)