博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Text Justification
阅读量:6758 次
发布时间:2019-06-26

本文共 2583 字,大约阅读时间需要 8 分钟。

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.

要考虑到各种特殊情况,以及怎样才能让空余出来的空格分布尽可能的平均。cnt用来记录当前行有多少个单词,len用来记录当前单词的长度和。注意处理完一行后要执行i--,要不然程序会跳过第pos行。a为每个间隙平均分配到的空格数,b为不能被整除而余下的空格数,将这b个分配给前b个间隙就行了。

1 class Solution { 2 public: 3     vector
fullJustify(vector
&words, int L) { 4 vector
res; 5 string s; 6 int pos = 0, cnt = 0; 7 int len = 0; 8 int a, b, c; 9 for (int i = 0; i < words.size(); ++i) {10 if (len + words[i].length() + cnt <= L) {11 ++cnt;12 len += words[i].length();13 } else {14 s += words[pos];15 if (cnt == 1) {16 c = L - len;17 for (int k = 0; k < c; ++k)18 s += ' ';19 } else {20 a = (L - len) / (cnt - 1);21 b = (L - len) % (cnt - 1);22 for (int j = 1; j < cnt; ++j) {23 c = a;24 if (j <= b) ++c;25 for (int k = 0; k < c; ++k) 26 s += ' ';27 s += words[pos+j];28 }29 }30 res.push_back(s);31 s.clear();32 pos = i--;33 cnt = 0;34 len = 0;35 }36 }37 s += words[pos];38 for (int j = 1; j < cnt; ++j) {39 s = s + ' ' + words[pos + j];40 }41 c = L - len - cnt + 1;42 for (int k = 0; k < c; ++k) {43 s += ' ';44 }45 res.push_back(s);46 return res;47 }48 };

 

转载地址:http://snweo.baihongyu.com/

你可能感兴趣的文章
两列布局——但只用右浮动
查看>>
GNOME 网页浏览器 Epiphany 将要进行 5 项改进
查看>>
今年CES最大亮点:智能语音助手正成为新趋势
查看>>
Windows Mysql Server重启, log-bin路径配置
查看>>
刘剑锋:友云采助力企业数字化采购的新发展
查看>>
Rainbond 5.0.4 发布,做最好用的云应用操作系统
查看>>
亚马逊宣布与西云数据达成合作,旨在进一步扩大中国业务
查看>>
java nio的基础--缓冲区
查看>>
负载均衡沙龙活动第二期现场问答汇集
查看>>
GBDT原理及利用GBDT构造新的特征-Python实现
查看>>
Android帧缓冲区(Frame Buffer)硬件抽象层(HAL)模块Gralloc的实现原理分析(10)...
查看>>
【Xamarin.Forms】在XAML中传递参数
查看>>
关于数据仓库 — 总体工具介绍
查看>>
最大的错误是不敢犯错
查看>>
跟我学交换机配置(七)
查看>>
makefile 中 $@ $^ % 2015-04-11 18:02:36
查看>>
C#强化系列文章三:实验分析C#中三种计时器使用异同点
查看>>
Linux 进程间通信(一)
查看>>
通用对象池ObjectPool的一种简易设计和实现方案
查看>>
HTTP压缩仍让加密连接处于风险之中
查看>>