LeetCode68——Text Justification
2015-11-02 10:34
183 查看
LeetCode68——Text Justification
也是相当恶心的一道题,倒不是有多难,还是不知道他的边界条件是怎么样的,所以也是经过多次的提交取改进代码,最后通过。
就不细说了,代码:
也是相当恶心的一道题,倒不是有多难,还是不知道他的边界条件是怎么样的,所以也是经过多次的提交取改进代码,最后通过。
就不细说了,代码:
class Solution { private: void removeBackSpace(string &s) { int i = s.size() - 1; while (i >= 0 && s[i] == ' ') { s.pop_back(); i--; } } public: vector<string> fullJustify(vector<string>& words, int maxWidth) { int i = 0; int lenSum = 0; int count = 0; int space; vector<string> result; while (i < words.size()) { int j = i; lenSum = 0; int tempSum = lenSum + j - i; while (j<words.size()&&tempSum <= maxWidth) { lenSum += words[j].size(); j++; tempSum = lenSum + j - i; } if (tempSum - 1 > maxWidth) { j--; lenSum -= (words[j].size()); } int distance = j - i; if (distance > 1) { if (j != words.size()) { space = (maxWidth - lenSum) / (distance - 1); vector<char> tempspace(space, ' '); string spaceWord(tempspace.begin(), tempspace.end()); string temp; for (int k = i; k < j; k++) { temp += words[k]; temp += spaceWord; } removeBackSpace(temp); if (temp.size() < maxWidth) { int count = maxWidth - temp.size(); for (int k = 0; count > 0 && k < temp.size(); k++) { if (temp[k] == ' ') { temp.insert(temp.begin() + k, ' '); k++; count--; continue; } } } result.push_back(temp); } else { space = 1; vector<char> tempspace(space, ' '); string spaceWord(tempspace.begin(), tempspace.end()); string temp; for (int k = i; k < j; k++) { temp += words[k]; temp += spaceWord; } removeBackSpace(temp); if (temp.size() < maxWidth) { int count = maxWidth - temp.size(); while (count > 0) { temp.insert(temp.end(), ' '); count--; } } result.push_back(temp); } } else if (distance == 1) { string temp = words[j - 1]; vector<char>tempspace(maxWidth-words[j-1].size(), ' '); string spaceWord(tempspace.begin(),tempspace.end()); temp += spaceWord; result.push_back(temp); } else { string temp = words[j]; vector<char>tempspace(maxWidth - words[j].size(), ' '); string spaceWord(tempspace.begin(), tempspace.end()); temp += spaceWord; result.push_back(temp); j++; } i = j; } return result; } };
相关文章推荐
- [Python开发] python使用nltk进行Chart Parsing
- MySQL安装失败问题解决
- 九宫格计算按钮frame的代码
- vector
- winform登录代码
- hdu 5532 Almost Sorted Array(LIS)
- ndroid提供了Animation,在Android SDK介绍了2种Animation模式:
- 广播
- 全球域名商解析新增保有量18强:5家中国域名商上榜
- dispatcherservlet详解
- Essential Studio Enterprise Edition 2015 v3正式发布[附下载]
- iOS播放音乐,毛玻璃效果,播放gif图,
- 速冻熟食制品的QS的申请办法
- img元素高度多出来的几像素
- iOS7上TableViewCell的button和UIImageView个别未显示的bug
- 认识HTTP
- 服务之远程服务
- Java 内存分配
- jquery append appendTo before after insertAfter insertBefore prepend prependTo用法区别
- 编写轻量ajax组件01-与webform平台上的各种实现方式比较