字节对齐
仅供学习,侵删
第二题:
现给出一组单词和行约束参数L,需要对文本进行处理,需求如下:
规整后输出的每行所包含的字符个数应等于L
每行文本包含尽可能多的单词,单词之间或行尾不足部分都以“”填充
如果一行有两个或两个以上的单词,则要求第一个单词和最后一个单词分别与左右边界对齐
一行内单词间的“”尽可能均匀分布。如果无法均匀分布,则左边可多于右边1个“”
最后一行的单词之间仅需一个“”
基本思路——遍历整个单词数组,并执行以下步骤:
求本行的单词个数以及单词的长度和
求均匀空格数和额外空格数
均匀填充单词
如果未填满,在末尾补空格
#include <iostream>
#include <string>
#include <vector>
using namespace std;
//
// Created by jt on 2020/9/25.
//
vector<string> fullJustify(vector<string> &words, int L) {
vector<string> res;
for (int start = 0, end; start < words.size(); start = end) {
int width = 0, spaces = 1, extra = 0;
// 定位本行的末尾单词(注意这里的end为末尾单词的后一个下标)
//width表示除了words[end]的单词加起来的长度,end-start表示填充*的至少个数,
for (end = start; end < words.size() && width + words[end].size() + (end-start) <= L; ++end) {
width += words[end].size();
}
// 求空格数和额外空格数
//如果一行有两个或两个以上的单词,则要求第一个单词和最后一个单词分别与左右边界对齐
//左边多于右边
if (end - start != 1 && end != words.size()) {
spaces = (L - width) / (end - start - 1);
extra = (L - width) % (end - start - 1);
}
// 填充本行字符串
string line(words[start]);
for (int i = start + 1; i < end; ++i) {
line += string(spaces, '*');
if (extra-- > 0) line += "*";
line += words[i];
}
// 填充末尾 *
line += string(L-line.size(), '*');
res.push_back(line);
}
return res;
}
int main()
{
cout << "Hello World";
vector<std::string> words;
words={"What","must","be","acknowledgment","shall","be"};
int L=16;
vector<string> res=fullJustify(words, L);
for( auto k:res)
{
cout<<k<<endl;
}
return 0;
}
————————————————
https://www.nowcoder.com/questionTerminal/e03feb44880d4254b19fbdf9d124cfe2?orderByHotValue=1&pos=197&mutiTagIds=579
版权声明:本文为CSDN博主「TheJayChou」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_32843395/article/details/119843826