Given an array of words and a length L, format the text such, all line have exactly L characters and is fully (left and right) justified.
You should pack your words in a greedy approach; That's, pack as many words as you can on each line. Pad extra spaces when necessary so, 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 does not divide evenly between words, the empty slots on the left would be assigned more SP Aces than the slots on the right.
For the last line of text, it should being justified and no extra space is inserted between words.
For example,
words:["This", "is", "an", "example", "of", "text", "justification."]
L: 16 .
Problem Solving Ideas:
The
is implemented directly by the constraints, and the Java implementation is as follows:
static public list<string> fulljustify (string[] words, int maxWidth) {list<string> list=new Array List<string> (); int start=0,end=-1,sum=0; for (int i=0;i<words.length;i++) {sum+=words[i].length (); if (sum>maxwidth) {i--; start=end+1; End=i; sum=0; List.add (onestring (words,start,end,maxwidth)); Continue } sum++; } if (sum>0) List.add (onestring (words,end+1,words.length-1,maxwidth)); return list; } static public String onestring (string[] words,int start,int end,int maxWidth) {StringBuilder sb=new StringBuilder ( ); if (start==end) sb.append (Words[start]); else if (end==words.length-1) {for (int i=start;i<=end-1;i++) sb.append (words[i]+ ""); Sb.append (Words[end]); } else{int spacesum=maxwidth; for (int i=start;i<=end;i++) spacesum-=words[i].length (); int extra=spacesum-(spacesum/(enD-start)) * (End-start); for (int i=start;i<=end;i++) {sb.append (words[i]); for (int j=0;j<spacesum/(end-start) &&i!=end;j++) sb.append (""); if (extra-->0) sb.append (""); }} while (Sb.length () <maxwidth) sb.append (""); return sb.tostring (); }
Java for Leetcode 068 Text Justification