Text Justification

来源:互联网 发布:哈利波特最后结局知乎 编辑:程序博客网 时间:2024/05/22 14:45

题目描述

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 L characters.
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.

题目解答

解题思路

一共有两种情况:

  • 如果是最后一行或者该行只有一个单词,采用左对齐,不插入多余空格,右边补全空格的方式;
  • 其它情况下,采用两端对齐,插入多余空格在中间的方式。(平均空格和额外的空格)

代码实现

public class Solution {     public List<String> fullJustify(String[] words, int maxWidth) {        if(words.length == 0)            return null;        List<String> ret = new ArrayList<>();        int i = 0;        int wordsLength = words.length;        while(i < wordsLength){            StringBuilder sb = new StringBuilder();            String temp = words[i];            sb.append(temp);            int tempLen = words[i].length();            int j = i + 1;            // j - i为空格数            while(j < wordsLength && (tempLen + words[j].length() + j - i) <= maxWidth){                tempLen += words[j++].length();            }            //该单词为独立一行            boolean isOneLine = (j == (i+1));            //最后一行            boolean isLastLine = (j == wordsLength);            //计算平均空格数和额外空格数            int averNUm = (isOneLine || isLastLine) ? 1 : (maxWidth - tempLen)/(j - i - 1);            int extraNUm = (isOneLine || isLastLine) ? 0 : (maxWidth - tempLen)%(j - i - 1);            //这里是核心部分            for(int k = i + 1; k < j; k++){                int num = extraNUm > 0 ? averNUm + 1 : averNUm;                addBlank(sb, num);                sb.append(words[k]);                extraNUm--;            }            addBlank(sb, maxWidth - sb.length());            ret.add(sb.toString());            i = j;        }        return ret;    }    public static void addBlank(StringBuilder sb, int num){        for(int i = 0; i < num; i++){            sb.append(" ");        }    }}
0 0