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.

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.

贪心算法,主要这几步骤:

使用字符串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;
}
};

最新文章

  1. MailKit---获取邮件
  2. 区块链(Blockchain)
  3. 编译Android AOSP代码
  4. ArcGIS Server,4000端口被占用
  5. Qlikview 的服务器
  6. test1
  7. Ant打jar包指定MainClass
  8. Cookie的基本使用
  9. html的显示消息和留言板
  10. 我的Chrome
  11. Android视频录制从不入门到入门系列教程(三)————视频方向
  12. [转] babel-plugin-react-css-modules配置
  13. AE插入音乐
  14. python核心技术
  15. checkbox在vue中的用法总结
  16. 阿里云上安装pip3(Ubuntu)
  17. MySQL分析数据运行状态利器【SHOW PROCESSLIST】
  18. as3.0中如何阻止事件冒泡
  19. linux命令学习之:echo
  20. 解决PHP在Windows IIS 上传的图片无法访问的问题

热门文章

  1. 复制到剪切板js代码(转)
  2. Photoshop的版本体系
  3. 应对Memcached缓存失效,导致高并发查询DB的几种思路
  4. node最简单的升级
  5. jquery省市选择案例
  6. 在Spark中自定义Kryo序列化输入输出API(转)
  7. session劫持技术
  8. Hydra 无法爆破SSH 解决办法
  9. 前端如何接收 websocket 发送过来的实时数据
  10. powerdesigner 16.5 破解步骤