Text Justification
来源:互联网 发布:重庆 外卖 大数据 编辑:程序博客网 时间:2024/05/18 02:19
Given an array of words and a 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 ''
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:
- 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.
-----SOLUTION-----
class Solution {public: vector<string> fullJustify(vector<string> &words, int L) { vector<string> result; string str; int startWord = 0; int nextWord = 0; int restLen; while(nextWord < words.size()) { startWord = nextWord; restLen = L - words[nextWord].length(); str = words[nextWord]; int newRestLen = restLen - words[nextWord].length()-1; while(++nextWord < words.size() ) { newRestLen = restLen - words[nextWord].length()-1; if(newRestLen < 0) break; restLen = newRestLen; } int wordInLine = nextWord-startWord; if(wordInLine == 1) { while(str.length() < L) str+= " "; result.push_back(str); continue; } else if(nextWord >= words.size()) { for(int i = 1; i< wordInLine; i++) { str+= " "; str+= words[startWord+i]; } while(str.length() < L) str+= " "; result.push_back(str); continue; } int spaceNum = restLen/(wordInLine-1); int wordOfMoreSpace = restLen - spaceNum*(wordInLine-1); spaceNum += 1; for(int i = 1; i<= wordOfMoreSpace; i++) { for(int j = 0; j<=spaceNum; j++) { str+= " "; } str+= words[startWord+i]; } for(int i = wordOfMoreSpace+1; i < wordInLine; i++) { for(int j = 0; j < spaceNum; j++) { str+= " "; } str+= words[startWord+i]; } result.push_back(str); } return result; }};
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- ubuntu 10.04 安装arm-linux-gcc
- html5 新元素使用规范解析图示,翻译。
- JS判断字符串是否包含某字符串 indexOf()方法使用
- BCD错误的修复和Win7启动备份方法
- IOS UIScrollView 说明 和 UIScrollViewDelegate详解
- Text Justification
- 双目视觉嵌入式移植成功
- 文本输入控件wx.TextCtrl
- SQL点滴21—几个有点偏的语句
- 单向链表操作函数
- ORA-12514(TNS:监听程序当前无法识别...)的解决方案
- android listview addHeaderView和addFooterView详解
- c++智能指针的实现
- CentOS中设置系统级代理