[LeetCode] Text Justification

简介: The key to this problem is to identify all the words that can be added to a line and then identify the places that require an additional space (to mak...

The key to this problem is to identify all the words that can be added to a line and then identify the places that require an additional space (to make the spaces as even as possible, we can only add an additional space if needed). This link has a brilliant solution that has a nice formula for the places that require an addtional space. The code is written as follows.

 1 class Solution {
 2 public:
 3     vector<string> fullJustify(vector<string>& words, int maxWidth) {
 4         int idx = 0, n = words.size();
 5         vector<string> justifications;
 6         while (idx < n) {
 7             int width = 0, numWords = 0;
 8             while (idx + numWords < n && width + words[idx + numWords].length() <= maxWidth - numWords) {
 9                 width += words[idx + numWords].length();
10                 numWords++;
11             }
12             string justification = words[idx];
13             for (int j = 0; j < numWords - 1; j++) {
14                 if (idx + numWords == n) justification += " ";
15                 else justification += string((maxWidth - width) / (numWords - 1) + (j < (maxWidth - width) % (numWords - 1)), ' ');
16                 justification += words[idx + j + 1];
17             }
18             justification += string(maxWidth - justification.length(), ' ');
19             justifications.push_back(justification);
20             idx += numWords;
21         }
22         return justifications;
23     }
24 };

 

目录
相关文章
|
算法
LeetCode 68. Text Justification
给定一个单词数组和一个宽度maxWidth,格式化文本,使每行具有正确的maxWidth字符并完全(左和右)对齐。
72 0
LeetCode 68. Text Justification
|
17天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-2
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
17天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-1
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
18天前
|
索引
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值
|
18天前
|
算法
【LeetCode刷题】滑动窗口解决问题:串联所有单词的子串(困难)、最小覆盖子串(困难)
【LeetCode刷题】滑动窗口解决问题:串联所有单词的子串(困难)、最小覆盖子串(困难)
|
18天前
|
算法 容器
【LeetCode刷题】滑动窗口解决问题:水果成篮、找到字符串中所有字母异位词
【LeetCode刷题】滑动窗口解决问题:水果成篮、找到字符串中所有字母异位词
|
18天前
【LeetCode刷题】专题三:二分查找模板
【LeetCode刷题】专题三:二分查找模板
【LeetCode刷题】专题三:二分查找模板
|
18天前
【LeetCode刷题】前缀和解决问题:742.寻找数组的中心下标、238.除自身以外数组的乘积
【LeetCode刷题】前缀和解决问题:742.寻找数组的中心下标、238.除自身以外数组的乘积
|
18天前
【LeetCode刷题】二分查找:寻找旋转排序数组中的最小值、点名
【LeetCode刷题】二分查找:寻找旋转排序数组中的最小值、点名