您的位置:首页 > 其它

[LeetCode]Text Justification

2015-12-18 20:30 232 查看
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 Lcharacters.

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:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> ret;
int idx = 0;
while(idx<words.size()){
int total = 0;
int end = idx;
while (end < words.size() && total+end-idx+words[end].length() <= maxWidth) {
total += words[end].length();
end ++;
} //把可以放在一行的单词位置记录下来 end 和 idx是结束和开始位置
string s = words[idx];
if (end == words.size() || end-idx==1) { //如果是最后一行或者只有一行
for (int i = idx+1; i < end; i ++)
s += " " + words[i];
s += string(maxWidth-(total+end-idx-1), ' ');
}
else {//如果不是
int base = (maxWidth-total)/(end-idx-1);//最基础的间隔格数
int left = (maxWidth-total)%(end-idx-1);//多余的格数,要放在左侧中
int count = 0;//统计多余的格数
for(int i=idx+1; i<end; ++i){
if(count<left) {
s += string(base+1,' ');
s += words[i];
++count;
}
else {
s+= string(base,' ');
s+= words[i];
}
}
}
ret.push_back(s);
idx = end;
}
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: