68. Text Justification
来源:互联网 发布:个人如何开通淘宝直播 编辑:程序博客网 时间:2024/06/06 03:40
Given an array of words and a length L, format the text such that each line has exactlyL 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 L 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.
class Solution {public: vector<string> fullJustify(vector<string>& words, int maxWidth) { vector<string> result; for(int i = 0,l,k; i < words.size(); i+=k){ for(l=k=0; (i+k < words.size())&&(l+words[i+k].size()<=maxWidth-k);k++){ l+=words[i+k].size(); } string tmp = words[i]; for(int j = 0; j < k-1; j++){ if(i + k >= words.size()){ tmp += " "; }else{ tmp += string((maxWidth-l)/(k-1)+(j<(maxWidth-l)%(k-1)),' '); } tmp += words[i+j+1]; } tmp += string(maxWidth - tmp.size(), ' '); result.push_back(tmp); //return result; } return result; }};
通过贪婪的算法,找出适当的字符串,然后在利用(maxWidth-l)/(k-1)+(j<(maxWidth-l)%(k-1)计算两个字符串之间的空格数量,最后一行是左对齐的。
- LeetCode 68. Text Justification
- LeetCode --- 68. Text Justification
- [Leetcode] 68. Text Justification
- [leetcode] 68.Text Justification
- 68. Text Justification
- 68. Text Justification
- [leetcode] 68. Text Justification
- LeetCode 68. Text Justification
- Leetcode 68. Text Justification
- LeetCode 68. Text Justification
- 68. Text Justification
- leetcode 68. Text Justification
- 68. Text Justification
- [LeetCode] 68. Text Justification
- LeetCode-68.Text Justification
- 68. Text Justification
- leetcode 68. Text Justification
- 68. Text Justification
- 《计算机网络》知识总结-5.TCP的研究学习思路
- 样本均值的特征与分布
- 实现支持2^n字节对齐分配的malloc和free函数
- nexus私服学习总结
- RequireJS:一款优秀的AMD模块加载器
- 68. Text Justification
- 利用SVN实现增量打包
- Java Web错误页面
- 树状数组入门之POJ 2352 Star
- 欢迎使用CSDN-markdown编辑器
- eclipse F3可以看到class的定义,但是编辑器里有叉叉,refers to type "", 类型不匹配
- swift 关于 CocoaPods引入Alamofire报警告问题
- Unity Shaders——屏幕特效混合模式(Blend mode with screen effects)
- Hadoop错误笔记