假设我们有一个单词列表和一个宽度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
让我们看下面的实现以更好地理解-
#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 ,]