首页 > 代码库 > Text Justification
Text Justification
Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ‘ ‘
when necessary so that each line has exactlyL characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left 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 is an", "example of text", "justification. " ]
Note: Each word is guaranteed not to exceed L in length.
- A line other than the last line might contain only one word. What should you do in this case?
In this case, that line should be left-justified.
没什么算法吧。。。题意开始理解错了, Extra spaces between words should be distributed as evenly as possible这句,英文不认识。。。初中刚毕业的英语水平混到现在简直是个奇迹0.0
直接贴代码吧,感觉写的有点屎
1 public ArrayList<String> fullJustify(String[] words, int L) { 2 ArrayList<String> result = new ArrayList<String>(); 3 for (int i = 0; i < words.length;) { 4 int start = i; 5 int end = i; 6 for (int j = i, count = -1; j <= words.length && count <= L; ++j, ++i) { 7 if (j < words.length) { 8 count += (1 + words[j].length()); 9 } 10 end = j - 1; 11 } 12 i--; 13 if (start == words.length - 1 || start == end) { 14 String re = words[start]; 15 for (int k = re.length(); k < L; k++) { 16 re += " "; 17 } 18 result.add(re); 19 if (start == words.length - 1) { 20 break; 21 } 22 } else { 23 if(end==words.length-1){ 24 String re = words[start]; 25 for(int k=start+1;k<=end;k++){ 26 re+=(" "+words[k]); 27 } 28 for (int k = re.length(); k < L; k++) { 29 re += " "; 30 } 31 result.add(re); 32 break; 33 } 34 int count = end - start; 35 int total = 0; 36 for (int k = start; k <= end; k++) { 37 total += words[k].length(); 38 } 39 total = L - total; 40 // total " " in count slot 41 String re = words[start]; 42 for (int k = start + 1; k <= end; k++) { 43 int p = total / count; 44 if (total%count != 0 && total > count && count > 1) { 45 p++; 46 } 47 for (int m = 0; m < p; m++) { 48 re += " "; 49 } 50 total -= p; 51 count--; 52 re += words[k]; 53 } 54 result.add(re); 55 } 56 } 57 return result; 58 }
各位看官就凑合看哈