1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
| package algorithm;
import java.util.ArrayList; import java.util.List;
public class TextJustification {
private static String fillWords(String[] words, int startIndex, int endIndex, int maxWidth, boolean lastLine) { int wordCount = endIndex - startIndex + 1; int spaceCount = maxWidth + 1 - wordCount; for (int i = startIndex; i <= endIndex; i++) { spaceCount -= words[i].length(); }
int spaceSuffix = 1; int spaceAvg = (wordCount == 1) ? 1 : spaceCount / (wordCount - 1); int spaceExtra = (wordCount == 1) ? 0 : spaceCount % (wordCount - 1);
StringBuilder ans = new StringBuilder(); for (int i = startIndex; i < endIndex; i++) { ans.append(words[i]); if (lastLine) { ans.append(' '); continue; } int temp = spaceSuffix + spaceAvg; if ((i - startIndex) < spaceExtra) { temp += 1; } while (temp-- > 0) { ans.append(' '); } } ans.append(words[endIndex]); int temp = maxWidth - ans.length(); while (temp-- > 0) { ans.append(' '); } return ans.toString(); }
public static List<String> fullJustify(String[] words, int maxWidth) { List<String> ans = new ArrayList<>(); int lineLength = 0; int startIndex = 0; for (int i = 0; i < words.length; i++) { lineLength += words[i].length() + 1;
if (i + 1 == words.length || lineLength + words[i + 1].length() > maxWidth) { ans.add(fillWords(words, startIndex, i, maxWidth, i + 1 == words.length)); startIndex = i + 1; lineLength = 0; } } return ans; }
public static void main(String[] args) { String[] words = new String[]{"This", "is", "an", "example", "of", "text", "justification."}; int maxWidth = 16; System.out.println(fullJustify(words, maxWidth));
words = new String[]{"What", "must", "be", "acknowledgment", "shall", "be"}; maxWidth = 16; System.out.println(fullJustify(words, maxWidth));
words = new String[]{"Science", "is", "what", "we", "understand", "well", "enough", "to", "explain", "to", "a", "computer.", "Art", "is", "everything", "else", "we", "do"}; maxWidth = 20; System.out.println(fullJustify(words, maxWidth));
} }
|