ProDeveloperTutorial.com

教程和国彩网解决方案
菜单
  • Shell脚本
  • 系统设计
  • Linux系统国彩网
  • 4g LTE
  • 编码问题
  • C
  • C ++
  • DSA
  • GIT

给定一个句子和maxWidth。以这样的方式排列文本,使得每行都具有完全maxWidth字符,这是C ++中的解决方案

前开发者教程 十二月31,2018
Example:
Input:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
Output:
[
   "This    is    an",
   "example  of text",
   "justification.  "
]

这个问题可以分为两个不同的部分。

在第一部分中,我们需要检查一行中可以容纳多少个单词。

在第二部分中,确定要在这些行之间平均插入的空间。为此,计算要引入的空格数,然后除以单词数。

需要考虑的一些极端情况:

  1. 每个单词之间至少应有一个空格。
  2. 如果一行只有一个单词,则应保持对齐。

C ++解决方案

#include<iostream>
#include<vector>
#include<string>

using namespace std;

vector<string> text_justification(vector<string> &words, int maxWidth)
{

	vector<string> result;
	for(int i = 0, w; i < words.size(); i = w) 
	{
		//reset width to 0. This width is checked with maxWidth
		int width = 0;

		//check how many words will fit into the line
		for(w = i; w < words.size() && width + words[w].size() + w - i <= maxWidth; w++) 
		{
			width += words[w].size();
		}


		int space = 1, extra = 0;
		if(w - i != 1 && w != words.size()) 
		{
			space = (maxWidth - width) / (w - i - 1);
			extra = (maxWidth - width) % (w - i - 1);
		}

		string line(words[i]);
		for(int k = i + 1; k < w; k++) 
		{
			line += string(space, ' ');
			if(extra-- > 0) 
			{
				line += " ";
			}
			line += words[k];
		}

		line += string(maxWidth - line.size(), ' ');
		result.push_back(line);
	}
	return result;

}




int main()
{

	vector<string> words = {"This", "is", "an", "example", "of", "text", "justification."};
	int maxWidth = 16;

	vector<string> result = text_justification(words, maxWidth);

	for (const auto& value : result) 
	{
    	cout << value << '\n';
	}

	return 0;
}

输出:

   "This    is    an",
   "example  of text",
   "justification.  "

该网站上可用的教程列表:

C国彩网20+章C ++国彩网80+章
100多个编码问题数据结构和算法85+章
系统设计20+章Shell脚本编写12章
4g LTE 60+章节最常见的编码问题
5G NR 50+章Linux系统国彩网20+章
分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

每天我们都会讨论竞争性国彩网问题,请加入我们的网站:   电报频道

ProDeveloperTutorial.com

教程和国彩网解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的



      <ol class="YhuRTun"><colgroup id="rrtqmau" class="ruUCRgA"><summary id="wKEE5jP"></summary></colgroup></ol>




                  <ins id="kyDEk82" class="kCEFo3w"></ins>