|
| 1 | +packagehard; |
| 2 | +importjava.util.*; |
| 3 | +/** |
| 4 | + * Created by fishercoder1534 on 10/9/16. |
| 5 | + */ |
| 6 | +publicclassTextJustification { |
| 7 | + |
| 8 | +publicstaticList<String>fullJustify(String[]words,intL) { |
| 9 | +ArrayList<String>result =newArrayList(); |
| 10 | +if(words ==null ||words.length ==0) |
| 11 | +returnresult; |
| 12 | +intcount =0; |
| 13 | +intlast =0; |
| 14 | +for(inti =0;i <words.length;i++){ |
| 15 | +if(count +words[i].length() + (i-last) >L){ |
| 16 | +intspaceNum =0 ; |
| 17 | +intextraNum =0; |
| 18 | +if(i -last -1 >0){ |
| 19 | +spaceNum = (L -count)/(i -last -1); |
| 20 | +extraNum = (L -count)%(i -last -1); |
| 21 | + } |
| 22 | +StringBuildersb =newStringBuilder(); |
| 23 | +for(intj =last;j <i;j++){ |
| 24 | +sb.append(words[j]); |
| 25 | +if(j <i-1){ |
| 26 | +for(intk =0;k <spaceNum;k++){ |
| 27 | +sb.append(" "); |
| 28 | + } |
| 29 | +if(extraNum >0){ |
| 30 | +sb.append(" "); |
| 31 | + } |
| 32 | +extraNum--; |
| 33 | + } |
| 34 | + } |
| 35 | +for(intj =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 | +StringBuildersb =newStringBuilder(); |
| 45 | +for(inti =last;i <words.length;i++){ |
| 46 | +sb.append(words[i]); |
| 47 | +if(sb.length() <L){ |
| 48 | +sb.append(" "); |
| 49 | + } |
| 50 | + } |
| 51 | +for(inti =sb.length();i <L;i++){ |
| 52 | +sb.append(" "); |
| 53 | + } |
| 54 | +result.add(sb.toString()); |
| 55 | +returnresult; |
| 56 | + } |
| 57 | + |
| 58 | +publicstaticvoidmain(String...args){ |
| 59 | +// String[] words = new String[]{"This", "is", "an", "example", "of", "text", "justification."}; |
| 60 | +String[]words =newString[]{"This","is","a","good","test!","\n","What","do","you","\n","think?","\n","I" |
| 61 | + ,"think","so","too!"}; |
| 62 | +intL =16; |
| 63 | +List<String>result =fullJustify(words,L); |
| 64 | +for(Stringstr :result) { |
| 65 | +System.out.println(str); |
| 66 | + } |
| 67 | + } |
| 68 | +} |