C++如何实现文本左右对齐
本文小编为大家详细介绍“C++如何实现文本左右对齐”,内容详细,步骤清晰,细节处理妥当,希望这篇“C++如何实现文本左右对齐”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
创新互联主要从事网站设计、网站制作、网页设计、企业做网站、公司建网站等业务。立足成都服务镇雄,十余年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18980820575
Text Justification 文本左右对齐
Example 1:
Input:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
Output:
[
"This is an",
"example of text",
"justification. "
]
Example 2:
Input:
words = ["What","must","be","acknowledgment","shall","be"]
maxWidth = 16
Output:
[
"What must be",
"acknowledgment ",
"shall be "
]
Explanation: Note that the last line is "shall be " instead of "shall be",
because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified becase it contains only one word.
Example 3:
Input:
words = ["Science","is","what","we","understand","well","enough","to","explain",
"to","a","computer.","Art","is","everything","else","we","do"]
maxWidth = 20
Output:
[
"Science is what we",
"understand well",
"enough to explain to",
"a computer. Art is",
"everything else we",
"do "
]
我将这道题翻译为文本的左右对齐是因为这道题像极了word软件里面的文本左右对齐功能,这道题我前前后后折腾了快四个小时终于通过了OJ,完成了之后想着去网上搜搜看有没有更简单的方法,搜了一圈发现都差不多,都挺复杂的,于是乎就按自己的思路来说吧,由于返回的结果是多行的,所以我们在处理的时候也要一行一行的来处理,首先要做的就是确定每一行能放下的单词数,这个不难,就是比较n个单词的长度和加上n - 1个空格的长度跟给定的长度L来比较即可,找到了一行能放下的单词个数,然后计算出这一行存在的空格的个数,是用给定的长度L减去这一行所有单词的长度和。得到了空格的个数之后,就要在每个单词后面插入这些空格,这里有两种情况,比如某一行有两个单词"to" 和 "a",给定长度L为6,如果这行不是最后一行,那么应该输出"to a",如果是最后一行,则应该输出 "to a ",所以这里需要分情况讨论,最后一行的处理方法和其他行之间略有不同。最后一个难点就是,如果一行有三个单词,这时候中间有两个空,如果空格数不是2的倍数,那么左边的空间里要比右边的空间里多加入一个空格,那么我们只需要用总的空格数除以空间个数,能除尽最好,说明能平均分配,除不尽的话就多加个空格放在左边的空间里,以此类推,具体实现过程还是看代码吧:
class Solution { public: vectorfullJustify(vector &words, int L) { vector res; int i = 0; while (i < words.size()) { int j = i, len = 0; while (j < words.size() && len + words[j].size() + j - i <= L) { len += words[j++].size(); } string out; int space = L - len; for (int k = i; k < j; ++k) { out += words[k]; if (space > 0) { int tmp; if (j == words.size()) { if (j - k == 1) tmp = space; else tmp = 1; } else { if (j - k - 1 > 0) { if (space % (j - k - 1) == 0) tmp = space / (j - k - 1); else tmp = space / (j - k - 1) + 1; } else tmp = space; } out.append(tmp, " "); space -= tmp; } } res.push_back(out); i = j; } return res; } };
读到这里,这篇“C++如何实现文本左右对齐”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注创新互联行业资讯频道。
新闻名称:C++如何实现文本左右对齐
文章URL:http://hbruida.cn/article/pscioc.html