C++程序:将单词转换为等长行进行文本两端对齐
假设我们有一组单词和一个宽度k,我们需要排列文本,使每一行正好包含k个字符,并且文本是完全对齐的。我们将尽可能多地将单词打包到每一行中。必要时,我们将添加额外的空格' ',以确保每一行正好包含k个字符。
单词之间的额外空格应尽可能均匀分布。如果一行上的空格数不能被单词数整除,则左侧的空位将分配比右侧空位更多的空格。对于最后一行文本,应左对齐,并且单词之间不插入额外空格。
因此,如果输入类似于["The", "grumpy", "wizards", "make", "toxic", "brew", "for", "the", "evil", "queen", "and", "Jack"],并且k = 13
则输出为:
The grumpy wizards make toxic brew for the evil queen and Jack
为了解决这个问题,我们将遵循以下步骤:
- 创建一个名为result的数组
- 对于范围从0到a的大小的i,用j更新i
- width := 0
- 对于范围从i到a的大小的j,并且width + a[j]的大小 + j – i <= b,
- width := width + a[j]的大小
- space := 1, extra := 0
- 如果j – 1 != 1 并且 j != a的大小,则
- space := (b - width) / (j – i – 1)
- extra := (b - width) % (j – i – 1)
- line := a[i]
- 对于范围从i + 1到j的k
- 将space个空格与line连接
- 如果extra > 0,则将一个空格与line连接
- 将extra减1
- line := 将a[k]与line连接
- x := line的大小
- line := 将(b - x)个空格与line连接
- 将line插入result
- 返回result
示例 (C++)
让我们看下面的实现来更好地理解:
#include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } void print_vector(vector<vector<auto> > v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << "["; for(int j = 0; j <v[i].size(); j++){ cout << v[i][j] << ", "; } cout << "],"; } cout << "]"<<endl; } class Solution { public: vector<string> fullJustify(vector<string> &a, int b) { vector <string> result; int i, j; for(i = 0; i < a.size(); i = j){ int width = 0; for(j = i; j < a.size() && width + a[j].size() + j - i <= b; j++){ width += a[j].size(); } int space = 1; int extra = 0; if(j - i != 1 && j != a.size()){ space = (b - width) / (j - i - 1); extra = (b - width) % (j - i - 1); } string line(a[i]); for(int k = i + 1; k < j; k++){ line += string(space, ' '); if(extra-- > 0){ line += " "; } line += a[k]; } int x = line.size(); line += string(b - x, ' '); result.push_back(line); } return result; } }; main(){ vector<string> v = {"The", "grumpy", "wizards", "make", "toxic", "brew", "for", "the", "evil", "queen", "and", "Jack"}; Solution ob; print_vector(ob.fullJustify(v, 13)); }
输入
["I", "love", "coding.", "here", "we", "will", "write", "some", "program"] 16
输出
[The grumpy, wizards make, toxic brew, for the evil, queen and, Jack ,]
广告