【LeetCode】68. Text Justification
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.
- 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.
贪心算法,主要这几步骤:
使用字符串line记录当前行
1、计算能否加入下一个单词word
2、若长度L能容纳,则加入line,并更新line长度
3、若长度L不能容纳,则line即为符合条件的一行,并重新调整单词间隔,构成newline
4、单词全部添加完毕,在newline尾部加入空格。
注意:添加最后一行
class Solution {
public:
vector<string> fullJustify(vector<string> &words, int L) {
vector<string> ret;
if(words.empty())
return ret;
string line = words[];
int len = words[].size();
int begin = ;
int end = ;
for(int i = ; i < words.size(); i ++)
{
len = len + + words[i].size();
if(len <= L)
{//can insert words[i]
line = line + " " + words[i];
}
else
{
len = len - - words[i].size();
end = i-;
int extraspaces = L - len;
string newline;
for(int j = begin; j < end; j ++)
{
string slot(ceil((double)extraspaces/(end-j)), ' ');
newline = newline + words[j] + " " + slot;
extraspaces -= slot.size();
}
newline += words[end];
string extraStr(L-newline.size(), ' ');
ret.push_back(newline+extraStr);
line = words[i];
len = words[i].size();
begin = i;
}
}
string extraStr(L-line.size(), ' ');
ret.push_back(line+extraStr); return ret;
}
};
最新文章
- MailKit---获取邮件
- 区块链(Blockchain)
- 编译Android AOSP代码
- ArcGIS Server,4000端口被占用
- Qlikview 的服务器
- test1
- Ant打jar包指定MainClass
- Cookie的基本使用
- html的显示消息和留言板
- 我的Chrome
- Android视频录制从不入门到入门系列教程(三)————视频方向
- [转] babel-plugin-react-css-modules配置
- AE插入音乐
- python核心技术
- checkbox在vue中的用法总结
- 阿里云上安装pip3(Ubuntu)
- MySQL分析数据运行状态利器【SHOW PROCESSLIST】
- as3.0中如何阻止事件冒泡
- linux命令学习之:echo
- 解决PHP在Windows IIS 上传的图片无法访问的问题