地址:http://oj.leetcode.com/problems/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.
思路:繁琐的字符串处理。算出每一行应该有几个单词,算好单词之间的空格。算每行有几个单词比较tricky,记得加上已有的单词数,因为单词之间至少一个空格。
注意最后一行的特殊处理。
WA了好多次,套用今天fenng在微薄上说的话(赚傻逼的钱不算真本事),这题错了这么多次,AC了不是真本事。
参考代码:
class Solution {
public:
vector<string> fullJustify(vector<string> &words, int L) {
vector<string>ans, vec;
int i = 0, len = 0, cnt = 0, space = 0, carry = 0;
while(i < words.size())
{
string str;
while(i < words.size() && len + cnt + words[i].length()<= L)
{
len += words[i].length();
++cnt;
vec.push_back(words[i++]);
}
if(cnt == 1)
{
str += vec[0];
while(str.length()<L)
{
str += ' ';
}
}
else
{
if(i>=words.size())
{
for(int j = 0; j<cnt; ++j)
{
str += vec[j];
if(j!=cnt-1)
{
str += ' ';
}
}
while(str.length()<L)
str += ' ';
ans.push_back(str);
break;
}
space = (L-len)/(cnt-1);
carry = (L-len)%(cnt-1);
for(int j = 0; j<cnt; ++j)
{
str += vec[j];
if(j < cnt-1)
{
for(int k = 0; k<space; ++k)
{
str += ' ';
}
}
if(carry)
{
str += ' ';
--carry;
}
}
}
ans.push_back(str);
len = cnt = carry = 0;
vec.clear();
}
return ans;
}
};
SECOND TRIAL, almost the same with last one.
class Solution {
public:
vector<string> fullJustify(vector<string> &words, int L) {
vector<string>ans;
if(words.empty())
return ans;
int i = 0, cnt = 0, j = 0, sz = 0, left = 0, quotient = 0;
while(i<words.size()) {
cnt = words[i].length();
j = i+1;
sz = 1;
string line = words[i];
while(j<words.size() && cnt + sz + words[j].length()<=L) {
cnt += words[j].length();
++j;
++sz;
}
if(sz==1) {
line.append(L-line.length(), ' ');
} else {
if(j>=words.size()) {
for(int k = 0; k<sz; ++k) {
if(k)
line+=words[i+k];
line+=' ';
}
line.append(L-line.length(), ' ');
ans.push_back(line);
break;
}
quotient = (L-cnt)/(sz-1);
left = (L-cnt)%(sz-1);
for(int k = 0; k<sz; ++k) {
if(k)
line += words[i+k];
if(k<sz-1)
line.append(quotient, ' ');
if(left) {
line += ' ';
--left;
}
}
}
ans.push_back(line);
i = j;
}
return ans;
}
};