标签:c style class blog code java
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.
click to show
corner cases.
Corner Cases:
- 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.
class Solution {public:
vector<
string> fullJustify(vector<
string> &words,
int L)
{
vector<
string> result;
int index=
0;
while(index<words.size())
{
vector<
string> line;
//find line words
int len=
0;
while(len==
0 || (len>
0 && words[index].length()+
1+len<=L))
{
if(line.size()!=
0)
{
line.push_back(
" ");
len++;
}
len=len+words[index].length();
line.push_back(words[index]);
index++;
if(index==words.size())
break;
}
//only 1 word
if(line.size()==
1)
{
string word=line[
0];
for(
int i=
0;i<L-line[
0].length();i++) word=word+
" ";
result.push_back(word);
}
//more words
else {
if(index!=words.size())
{
int i=
1;
while(len<L)
{
line[i]=line[i]+
" ";
len++;
//find a space
i=i+
2;
if(i>=line.size()) i=
1;
}
}
else {
int i=line.size()-
1;
while(len<L)
{
line[i]=line[i]+
" ";
len++;
}
}
string strline;
for(
int i=
0;i<line.size();i++)
strline=strline+line[i];
result.push_back(strline);
}
}
return result;
}
};
Text Justification,布布扣,bubuko.com
Text Justification
标签:c style class blog code java
原文地址:http://www.cnblogs.com/erictanghu/p/3759471.html