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 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.
分析:先拿到能够放在一起的words,然后在加padding
1 public class Solution { 2 public List<String> fullJustify(String[] words, int maxWidth) { 3 int left = 0; 4 List<String> result = new ArrayList<>(); 5 6 while (left < words.length) { 7 int right = findRight(left, words, maxWidth); 8 result.add(justify(left, right, words, maxWidth)); 9 left = right + 1; 10 } 11 return result; 12 } 13 14 private int findRight(int left, String[] words, int maxWidth) { 15 int right = left, sum = 0; 16 17 while (right < words.length && (sum + words[right].length()) <= maxWidth) { 18 sum += 1 + words[right].length(); 19 right++; 20 } 21 return right - 1; 22 } 23 24 private String justify(int left, int right, String[] words, int maxWidth) { 25 if (right - left == 0) return padResult(words[left], maxWidth); 26 27 boolean isLastLine = right == words.length - 1; 28 int numSpaces = right - left; 29 int totalSpace = maxWidth - wordsLength(left, right, words); 30 31 String space = isLastLine ? " " : blank(totalSpace / numSpaces); 32 int remainder = isLastLine ? 0 : totalSpace % numSpaces; 33 34 StringBuilder result = new StringBuilder(); 35 for (int i = left; i <= right; i++) { 36 result.append(words[i]).append(space).append(remainder-- > 0 ? " " : ""); 37 } 38 39 return padResult(result.toString().trim(), maxWidth); 40 } 41 42 private int wordsLength(int left, int right, String[] words) { 43 int wordsLength = 0; 44 for (int i = left; i <= right; i++) { 45 wordsLength += words[i].length(); 46 } 47 return wordsLength; 48 } 49 50 private String padResult(String result, int maxWidth) { 51 return result + blank(maxWidth - result.length()); 52 } 53 54 private String blank(int length) { 55 char[] charArray = new char[length]; 56 Arrays.fill(charArray, ' '); 57 return new String(charArray); 58 } 59 }

浙公网安备 33010602011771号