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 exactly L 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.
解题思路:
感觉这道题难就难在很繁琐....各种要求...当然我的代码写的也很冗长。具体思路就是每次判断说加入某个词之后长度会不会超出了,会的话就停止加入,将原来的转成一个String,然后再进行下一次的遍历。
public class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
if(words == null || words.length == 0)
return new ArrayList<String>();
int len = words.length;
int index = 0;
int num = 0;
int length1 = 0;
int length2 = 0;
List<String> result = new ArrayList<String>();
List<String> strsub = new ArrayList<String>();
while(index < len)
{
int strlen = words[index].length();
if(length1 + strlen <=maxWidth)
{
strsub.add(words[index]);
length1 += strlen+1;
length2 += strlen;
index ++;
}
else
{
int spacenum = maxWidth - length2;
String f = "";
while(!strsub.isEmpty())
{
int size = strsub.size() -1 ;
int snum;
if(size == 0)
snum = spacenum;
else
{
snum = spacenum/size;
if(spacenum%size != 0)
snum += 1;
}
spacenum -= snum;
f+=strsub.remove(0);
for(int i= 0;i<snum;i++)
f+=" ";
}
result.add(f);
strsub.clear();
length1 = 0;
length2 = 0;
}
}
if(!strsub.isEmpty())
{
int spacenum = maxWidth - length2;
String f = "";
while(!strsub.isEmpty())
{
int size = strsub.size() -1;
int snum;
if(size == 0)
snum = spacenum;
else
{
snum = spacenum/size;
if(spacenum%size != 0)
snum += 1;
}
spacenum -= snum;
f= f+strsub.remove(0);
if(f.length()<maxWidth)
f += " ";
}
while(f.length() <maxWidth)
f += " ";
result.add(f);
}
return result;
}
}