[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
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:
L:
Return the formatted lines as:
Note: Each word is guaranteed not to exceed L in length.
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; } };
相关文章推荐
- C# DataGridView 与 DataSet
- 虚拟化三剑客专题-XenServer(上)
- 以mysql为数据源的Solr配置
- ubuntu14.04中安装opencv2.4.9
- 12 UITableView编辑和移动 、UITableViewController、(+UIDatePicker)
- 虚拟化三剑客专题-XenServer(中)
- DataSet之增删改查操作(DataGridView绑定)
- 为什么在linux的命令行中cd .. 能返回上层目录
- 虚拟化三剑客专题-XenServer(中)
- 大话设计模式之代理模式
- 11 UITableView表视图
- UIPickerView
- [置顶] 屏幕适配 部分知识点总结,CSDN小冰原创
- Exchange2013/2016下通过RDB(恢复数据库)还原用户邮箱数据
- 面试总结1
- java学习之内部类
- UIStoryboard和UIResponder
- GPU 属性
- linux学习笔记(14)命令行下截屏scrot
- UIImageView和UIImage