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 .
Return the formatted lines as:
[ "This was an", "example of text", " justification. "]
Note:each word is guaranteed isn't to exceed L in length.
The problem is to give some words and a maximum number of letters n, and then use the greedy algorithm, let these words form a number of sentences, the length of these sentences can not exceed n, and each word to have a space, and should be the average allocation of space, if the distribution is uneven, then the front of the empty aligning behind the more. There is the last sentence should be the last space.
In fact, it is not difficult, the basic application of greedy algorithm.
Public classSolution { PublicList<string> fulljustify (string[] words,intmaxWidth) {List<String> result =NewArraylist<string>(); intnum = 0, j = 0, space = 0,pos = 0,more = 0; int[] ans =New int[Maxwidth+1]; Char[] Ch =New Char[MaxWidth]; inti = 0; while(i<words.length) {J= 0; Num= 0; while(I < words.length && num+words[i].length () <=maxWidth) {num+=words[i].length (); ANS[J]=i; I++; J++; Num++; } POS= 0; if(i = =words.length) {Space= 1; more= maxwidth-num; }Else if(J = = 1) {Space= maxwidth-num+J; more= 0; }Else{Space= (maxwidth-num+j)/(j-1); more= (maxwidth-num+j)% (j-1); } for(intK = 0;k<j;k++){ for(intA = 0;a<words[ans[k]].length (); a++,pos++) Ch[pos]=Words[ans[k]].charat (a); for(intA = 0;a<space && pos < maxwidth;a++,pos++) Ch[pos]= ' '; if(More > 0 && pos < maxWidth && i!=words.length) {Ch[pos]= ' '; more--; POS++; } if(i = = words.length && k = = J-1){ for(intA = 0;a<more;a++,pos++) Ch[pos]= ' '; }} result.add (String.valueof (Ch)); } returnresult; }}
Leetcode Text Justification-----java