您的位置:首页 > 其它

leetcode 068 —— Text Justification

2015-07-29 21:09 369 查看
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.

思路:此题也是极为复杂,以下代码写的很拙劣,等待后续的修改吧。

class Solution {
public:
int num = 0;
vector<string> fullJustify(vector<string>& words, int maxWidth) {
int n = words.size();
vector<string> res;
vector<int> len(n, 0);
for (int i = 0; i < n; i++)
len[i] = words[i].size();

int i = 0;

while (i < n){
int j = i;
int sum =len[i]+1;
while ( j < n &&sum <= maxWidth + 1){
j++;
if (j == n) break;
sum = sum + len[j] + 1;
}
sum = 0;
for (int k = i; k < j; k++)
sum += len[k];
int d = maxWidth - sum; //需要加空格的总数
//////////////////////////////////////////////////////////////////
if (j == n){
string s5;
if (len[i] == maxWidth){
res.push_back(words[i]);
return res;
}
cout << "aa" << s5 << "bb" << endl;
int cnt=0;
for (int k = i; k <j&&s5.size()<maxWidth; k++){
if (words[k].empty()) {
cnt++; //记录空字符串的个数
continue;
}
s5 = s5 + words[k] + ' ';
}
cout << "aa" << s5 << "bb" << endl;
cout << d << endl;
string s4(d + i+cnt - j, ' ');
s5 += s4;
res.push_back(s5);
cout << "aa" << s5 << "bb" << endl;
return res;
}
///////////////////////////////////////////////////////////////////
if (j - i == 1){ //只有一个串的情况
string s3 (d, ' ');
res.push_back(words[i] + s3);
i = j;
continue;
}

int a = d / (j - i - 1); //间隔之间至少要有的空格数量
int b = d % (j - i - 1); //左侧多一个空格的间隔的数量
string s1(a + 1, ' ');
string s2(a, ' ');
string s;
for (int k = i; k < i + b; k++)
s = s + words[k] + s1;
for (int k = i + b; k < j - 1; k++)
s = s + words[k] + s2;
s += words[j - 1];
res.push_back(s);

i = j;
}
return res;
}
}a;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: