Text Justification greedy
来源:互联网 发布:黄海波真相 知乎 编辑:程序博客网 时间:2024/06/06 12:46
思路:
贪心。时间复杂度O(N),空间复杂度O(1)。
class Solution {private:/** add space to a target line @param s : target line @param i : current space's number @param n : interspace sum @param L : space sum @param is_last : whether is the last line @return*/void addSpaces(string &s, int i, int n, int L, bool is_last) { if(n < 1 || i > n - 1) return; int spaces = is_last ? 1 : (L/n + (i < (L%n) ? 1 : 0)); s.append(spaces, ' ');}/** connect words[begin, end] to a line @param words @param begin @param end @param len : the length of words[begin, end] @param maxWidth @param is_last : whether if is the last line @return the connected line*/string connect(vector<string> &words, int begin, int end, int len, int maxWidth, bool is_last) { string s; int n = end - begin + 1;// words number for(int i = 0; i < n; ++i) { s += words[begin + i]; addSpaces(s, i, n - 1, maxWidth - len, is_last); } if(s.size() < maxWidth) { s.append(maxWidth - s.size(), ' '); } return s;}public: vector<string> fullJustify(vector<string>& words, int maxWidth) { vector<string> res; const int n = words.size(); int begin = 0, len = 0;//current line's starting point, current line's length for(int i = 0; i < n; ++i) { if(len + words[i].size() + (i - begin) > maxWidth) { res.push_back(connect(words, begin, i-1, len, maxWidth, false)); begin = i; len = 0; } len += words[i].size(); } res.push_back(connect(words, begin, n-1, len, maxWidth, true)); return res; }};
0 0
- Text Justification greedy
- 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
- Linux的用户目录
- ant的ant任务
- 堆区与栈区的区别
- 关于Spring中的context:property-placeholder 导入多个独立的配置文件
- Cocos code ide 常见问题
- Text Justification greedy
- VSync Count 垂直同步
- webserver 两种模式
- yarn timeline 服务
- 黑马程序员_基础语法笔记
- 语言[C/C++]_按位与、或、异或等运算方法
- 【Java】利用正则表达式判断是否为网址
- Cocos code ide 1.0.0 RC0 使用教程
- MySQL 添加列,修改列,删除列