|
| 1 | +package hard; |
| 2 | +import java.util.*; |
| 3 | +/** |
| 4 | + * Created by fishercoder1534 on 10/9/16. |
| 5 | + */ |
| 6 | +public class TextJustification { |
| 7 | + |
| 8 | + public static List<String> fullJustify(String[] words, int L) { |
| 9 | + ArrayList<String> result = new ArrayList(); |
| 10 | + if(words == null || words.length == 0) |
| 11 | + return result; |
| 12 | + int count = 0; |
| 13 | + int last = 0; |
| 14 | + for(int i = 0; i < words.length; i++){ |
| 15 | + if(count + words[i].length() + (i-last) > L){ |
| 16 | + int spaceNum = 0 ; |
| 17 | + int extraNum = 0; |
| 18 | + if(i - last - 1 > 0){ |
| 19 | + spaceNum = (L - count)/(i - last - 1); |
| 20 | + extraNum = (L - count)%(i - last - 1); |
| 21 | + } |
| 22 | + StringBuilder sb = new StringBuilder(); |
| 23 | + for(int j = last; j < i; j++){ |
| 24 | + sb.append(words[j]); |
| 25 | + if(j < i-1){ |
| 26 | + for(int k = 0; k < spaceNum; k++){ |
| 27 | + sb.append(" "); |
| 28 | + } |
| 29 | + if(extraNum > 0){ |
| 30 | + sb.append(" "); |
| 31 | + } |
| 32 | + extraNum--; |
| 33 | + } |
| 34 | + } |
| 35 | + for(int j = sb.length(); j < L; j++){ |
| 36 | + sb.append(" "); |
| 37 | + } |
| 38 | + result.add(sb.toString()); |
| 39 | + count = 0; |
| 40 | + last = i; |
| 41 | + } |
| 42 | + count += words[i].length(); |
| 43 | + } |
| 44 | + StringBuilder sb = new StringBuilder(); |
| 45 | + for(int i = last; i < words.length; i++){ |
| 46 | + sb.append(words[i]); |
| 47 | + if(sb.length() < L){ |
| 48 | + sb.append(" "); |
| 49 | + } |
| 50 | + } |
| 51 | + for(int i = sb.length(); i < L; i++){ |
| 52 | + sb.append(" "); |
| 53 | + } |
| 54 | + result.add(sb.toString()); |
| 55 | + return result; |
| 56 | + } |
| 57 | + |
| 58 | + public static void main(String...args){ |
| 59 | +// String[] words = new String[]{"This", "is", "an", "example", "of", "text", "justification."}; |
| 60 | + String[] words = new String[]{"This", "is", "a", "good", "test!", "\n", "What", "do", "you", "\n", "think?", "\n", "I" |
| 61 | + , "think", "so", "too!"}; |
| 62 | + int L = 16; |
| 63 | + List<String> result = fullJustify(words, L); |
| 64 | + for(String str : result) { |
| 65 | + System.out.println(str); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments