leetcode 68 Text Justification ----- java

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.

  这道题的意思就是给定一些单词和一个最大字母数n,然后用贪心算法,让这些单词组成数个句子,这些句子的长度不能超过n,并且每个单词之间要有空格,而且应当是平均分配空格,如果分配不均匀,那么是前面的空格比后面的多。还有就是最后一个句子应当是最后是空格。

其实不算难,基本的贪心算法的应用。

public class Solution {
    public List<String> fullJustify(String[] words, int maxWidth) {
        
        List<String> result = new ArrayList<String>();
        int num = 0, j = 0 ,space = 0,pos = 0,more = 0;
        int[] ans = new int[maxWidth+1];
        char[] Ch = new char[maxWidth];
        int i = 0;
        while(i<words.length){
            j = 0;
            num = 0;
               while( i < words.length && num+words[i].length()<=maxWidth    ){
                   num+=words[i].length();
                   ans[j] = i;
                   i++;
                   j++;
                   num++;
               }
               pos = 0;
               if( i == words.length){
                   space = 1;
                   more = maxWidth-num;
               }else if( j == 1){
                   space = maxWidth-num+j;
                   more = 0;
               }else{
                   space = (maxWidth-num+j)/(j-1);
                   more = (maxWidth-num+j)%(j-1);
               }
               for( int k = 0;k<j;k++){
                   for( int a = 0;a<words[ans[k]].length();a++,pos++)
                       Ch[pos] = words[ans[k]].charAt(a);
                   for( int a = 0;a<space && pos < maxWidth;a++,pos++)
                       Ch[pos] = ' ';
                   if( more > 0 && pos < maxWidth && i!= words.length){
                       Ch[pos] = ' ';
                       more--;
                       pos++;
                   }
                   if( i == words.length && k == j-1){
                       for( int a = 0;a<more;a++,pos++)
                           Ch[pos] = ' ';
                   }
                   
               }
               result.add(String.valueOf(Ch));

        }
        
        return result;
    }
}
原文地址:https://www.cnblogs.com/xiaoba1203/p/5950358.html