leecode 解题总结:68. Text Justification

#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
/*
问题:
Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly L characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

For the last line of text, it should be left justified and no extra space is inserted between words.

For example,
words: ["This", "is", "an", "example", "of", "text", "justification."]
L: 16.

Return the formatted lines as:
[
   "This    is    an",
   "example  of text",
   "justification.  "
]
Note: Each word is guaranteed not to exceed L in length.

分析:justified:合理的,pad:填塞
这是一个格式化输出的问题。本质上给定一个字符串数组和一个长度L,
1】需要摆放后每一行的长度都是L,如果不足L,需要填充空字符。
2】需要在一行中尽可能多的填充单词。
3】填充的空格需要尽可能左右两边相等,如果填充的空格部分不等,左边
   的空格可以比右边的多一些。
4】最后一行需要全部放置在左边,并且不能有额外的空格在单词之间。
这是否意味着最后一行只能放一个单词?然后不足的部分全部在右侧填充空格
理解错了,最后一行左对齐,并且单词之间不需要空格。说明是可以存放多个
单词的。

本质要使行数最少吧应该。
是否是贪心?每一行尽可能存放多个单词,这样留给剩余行摆放的单词越少,
剩余使用的行越少。
贪心问题。每一行摆放的时候,如果当前不是最后一行,那么每次摆放一个单词,需要
计算待摆放单词+至少一个空格得到的长度看是否<=L,如果符合,继续尝试下一个;
否则,说明当前行已经不能摆放了,重新开辟下一行。
如果发现待摆放单词是最后一个单词,且能在当前行摆放,则说明当前行是最后一行,
则直接讲改行所有单词拼接,最后拼接空格。

输入:
7(单词个数) 16(最大宽度)
This is an example of text justification.
输出:
This    is    an
example  of text
justification.  

关键:
1 如果只有一个空字符串,长度为0,应该直接返回空字符串数组
2 最后一行左对齐,也需要空格
Input:
["What","must","be","shall","be."]
12
Output:
["What must be","shallbe.    "]
Expected:
["What must be","shall be.   "]
3一种简单做法,每一行添加一个单词,剩余空格数减1
另外空格可以由:string(n , ' ')来生成
*/

class Solution {
public:
	string getSpaceStr(int spaceNum)
	{
		if(spaceNum <= 0)
		{
			return "";
		}
		stringstream stream;
		for(int i = 0 ; i < spaceNum; i++)
		{
			stream << ' ';
		}
		return stream.str();
	}

	string getLine(vector<string> words)
	{
		if(words.empty())
		{
			return "";
		}
		int size = words.size();
		stringstream stream;
		for(int i = 0 ; i < size ; i++)
		{
			stream << words.at(i);
		}
		return stream.str();
	}

	string getLineWithSpace(vector<string> words)
	{
		if(words.empty())
		{
			return "";
		}
		int size = words.size();
		stringstream stream;
		for(int i = 0 ; i < size ; i++)
		{
			if(i != size - 1)
			{
				stream << words.at(i) << ' ';
			}
			else
			{
				stream << words.at(i);
			}
		}
		return stream.str();
	}

	//根据每一行分组后的结果,生成最终结果
	vector<string> generate(vector<string>& words, int maxWidth , vector< vector<string> >& lines)
	{
		vector<string> result;
		if(lines.empty())
		{
			return result;
		}
		//组装结果,对除最后一行外的计算空格
		int lineSize = lines.size();
		int wordNum = 0;
		int spaceGroup = 0;
		int avgSpaceNum = 0;
		int countLen = 0;
		int spaceLen = 0;
		int remainSpaceNum = 0;
		int realSpaceNum = 0;
		string strSpace;
		int k = 0;
		string lineResult;
		for(int i = 0 ; i < lineSize - 1 ; i++ )
		{
			wordNum = lines.at(i).size();
			spaceGroup = wordNum - 1;//空格组数为单词个数-1
			countLen = 0;
			//统计单词长度
			for(int j = 0 ; j < wordNum ; j++ )
			{
				countLen += lines.at(i).at(j).length();
			}
			spaceLen = maxWidth - countLen;
			//只有一个单词
			if(spaceGroup == 0)
			{
				strSpace = getSpaceStr(spaceLen);
				lineResult = lines.at(i).at(0) + strSpace;
				result.push_back(lineResult);
				continue;
			}
			avgSpaceNum = spaceLen / spaceGroup;//可能有0组,说明只有一个单词
			remainSpaceNum = maxWidth - spaceGroup * avgSpaceNum - countLen;//别忘记减去单词本身长度
			//修改单词
			k = 0;
			while(remainSpaceNum > 0)
			{
				realSpaceNum = avgSpaceNum + 1;
				remainSpaceNum--;
				strSpace = getSpaceStr(realSpaceNum);
				if(k >= wordNum)
				{
					break;
				}
				//附加在单词之后
				lines.at(i).at(k++) += strSpace;
			}
			//最后一个单词没有空格
			while(k < wordNum - 1)
			{
				strSpace = getSpaceStr(avgSpaceNum);
				lines.at(i).at(k++) += strSpace;
			}
			lineResult = getLine(lines.at(i));
			result.push_back(lineResult);
		}
		//对最后一行,直接合并,字后一行两个单词间需要空格

		lineResult = getLineWithSpace(lines.at(lines.size() - 1));
		//看最后一行是否需要添加空格
		int tempLen = lineResult.length();
		if(tempLen < maxWidth)
		{
			strSpace = getSpaceStr(maxWidth - tempLen);
			lineResult += strSpace;
		}
		result.push_back(lineResult);
		return result;
	}

    vector<string> fullJustify(vector<string>& words, int maxWidth) 
	{
		vector<string> result;
        if(words.empty() )
		{
			return result;
		}
		if(maxWidth <= 0)
		{
			result.push_back("");
			return result;
		}
		//接下来就是摆放
		int size = words.size();
		int curLen = 0;
		int i = 0;
		int insertLen = 0;
		int lineNum = 0;
		vector< vector<string> > lines;//每一行存放该行可以摆放的位置
		while(i < size)
		{
			//计算当前单词长度
			while(i < size && curLen <= maxWidth)
			{
				insertLen = words.at(i).length() + 1;//注意最后一个单词可以不加空格
				//如果当前行能摆放,则就将当前单词插入到该行对应的结果集中
				//第一个待插入单词,长度为其本身;非第一个单词,需要多加一个空格的长度
				if(0 == curLen)
				{
					insertLen--;
				}
				if(insertLen + curLen <= maxWidth)
				{
					if(lines.empty())
					{
						vector<string> line;
						line.push_back(words.at(i));
						lines.push_back(line);
					}
					else
					{
						lines.at( lines.size() - 1 ).push_back( words.at(i) );
					}
				}
				//如果当前行不能摆放,就将最后的单词放到下一行中,这里需要直接退出,
				else
				{
					vector<string> line;
					line.push_back(words.at(i));
					lines.push_back(line);
					curLen = insertLen - 1;//重新设定新插入的长度
					i++;
					break;
				}
				curLen += insertLen;
				i++;
			}
		}
		result = generate(words , maxWidth , lines);
		return result;
    }
};

void print(vector<string>& result)
{
	if(result.empty())
	{
		cout << "no result" << endl;
		return;
	}
	int size = result.size();
	for(int i = 0 ; i < size ; i++)
	{
		cout << result.at(i) << endl ;
	}
}

void process()
{
	 vector<string> nums;
	 string value;
	 int num;
	 int maxWidth;
	 Solution solution;
	 vector<string> result;
	 while(cin >> num >> maxWidth)
	 {
		 nums.clear();
		 for(int i = 0 ; i < num ; i++)
		 {
			 cin >> value;
			 nums.push_back(value);
		 }
		 result = solution.fullJustify(nums , maxWidth);
		 print(result);
	 }
}

int main(int argc , char* argv[])
{
	process();
	getchar();
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
基于Django+python编写开发的毕业生就业管理系统支持学生教师角色+db数据库(毕业设计新项目).zip 【备注】 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用!有问题请及时沟通交流。 2、适用人群:计算机相关专业(如计科、信息安全、数据科学与大数据技术、人工智能、通信、物联网、自动化、电子信息等)在校学生、专业老师或者企业员工下载使用。 3、用途:项目具有较高的学习借鉴价值,不仅适用于小白学习入门进阶。也可作为毕设项目、课程设计、大作业、初期项目立项演示等。 4、如果基础还行,或热爱钻研,亦可在此项目代码基础上进行修改添加,实现其他不同功能。 欢迎下载!欢迎交流学习!不清楚的可以私信问我! 基于Django+python编写开发的毕业生就业管理系统支持学生教师角色+db数据库(毕业设计新项目).zip基于Django+python编写开发的毕业生就业管理系统支持学生教师角色+db数据库(毕业设计新项目).zip基于Django+python编写开发的毕业生就业管理系统支持学生教师角色+db数据库(毕业设计新项目).zip基于Django+python编写开发的毕业生就业管理系统支持学生教师角色+db数据库(毕业设计新项目).zip基于Django+python编写开发的毕业生就业管理系统支持学生教师角色+db数据库(毕业设计新项目).zip基于Django+python编写开发的毕业生就业管理系统支持学生教师角色+db数据库(毕业设计新项目).zip基于Django+python编写开发的毕业生就业管理系统支持学生教师角色+db数据库(毕业设计新项目).zip基于Django+python编写开发的毕业生就业管理系统支持学生教师角色+db数据库(毕业设计新项目).zip基于Django+python编写开发的毕业生就业管理系统支持学生教师角色+db数据库(毕业设计新项目).zip
毕设新项目基于python3.7+django+sqlite开发的学生就业管理系统源码+使用说明(含vue前端源码).zip 【备注】 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用!有问题请及时沟通交流。 2、适用人群:计算机相关专业(如计科、信息安全、数据科学与大数据技术、人工智能、通信、物联网、自动化、电子信息等)在校学生、专业老师或者企业员工下载使用。 3、用途:项目具有较高的学习借鉴价值,不仅适用于小白学习入门进阶。也可作为毕设项目、课程设计、大作业、初期项目立项演示等。 4、如果基础还行,或热爱钻研,亦可在此项目代码基础上进行修改添加,实现其他不同功能。 欢迎下载!欢迎交流学习!不清楚的可以私信问我! 学生就业管理系统(前端) ## 项目开发环境 - IDE: vscode - node版本: v12.14.1 - npm版本: 6.13.4 - vue版本: @vue/cli 4.1.2 - 操作系统: UOS 20 ## 1.进入项目目录安装依赖 ``` npm install ``` ## 2.命令行执行进入UI界面进行项目管理 ``` vue ui ``` ## 3.编译发布包(请注意编译后存储路径) #### PS:需要将编译后的包复制到后端项目的根目录下并命名为'static' 学生就业管理系统(后端) ## 1.项目开发环境 - IDE: vscode - Django版本: 3.0.3 - Python版本: python3.7.3 - 数据库 : sqlite3(测试专用) - 操作系统 : UOS 20 ## 2.csdn下载本项目并生成/安装依赖 ``` pip freeze > requirements.txt pip install -r requirements.txt ``` ## 3.项目MySQL数据库链接错误 [点击查看解决方法](https://www.cnblogs.com/izbw/p/11279237.html)
import PySimpleGUI as sg layout1 = [ [sg.T("请输入挡土墙参数",text_color="red",size=30,font=10,justification="center",pad=(10))], [sg.Text('内斜坡高度(m)',size=30),sg.InputText(size=5,key="a")],[sg.Text('挡土墙顶部到墙趾高度(m)',size=30), sg.InputText(size=5,key="b")], [sg.Text('顶面荷载边缘距离内边坡的水平距离(m)',size=30), sg.InputText(size=5,key="c")],[sg.Text('内边坡宽度(m)',size=30), sg.InputText(size=5,key="d")], [sg.Text('列车荷载分布宽度(m)',size=30), sg.InputText(size=5,key="e")],[sg.Text('墙背倾角(°)',size=30), sg.InputText(size=5,key="f")], [sg.Text('墙底倾斜角度(°)',size=30), sg.InputText(size=5,key="g")],[sg.Text('墙背与土体摩擦角(°)',size=30), sg.InputText(size=5,key="h")], [sg.Text('挡土墙底部水平宽度(m)',size=30), sg.InputText(size=5,key="i")],[sg.Text('挡土墙重度(γ/m³)',size=30), sg.InputText(size=5,key="j")], [sg.Text('基底摩擦系数设计值',size=30),sg.InputText(size=5,key="k")] ] layout2=[ [sg.T('请输入随机变量统计特征',text_color="red",font=10,justification="center",size=30,pad=(10,10))], [sg.Text('土体重度平均值',size=30),sg.InputText(size=5)],[sg.Text('土体重度标准差',size=30),sg.InputText(size=5)],[sg.Text('土体内摩擦角平均值',size=30),sg.InputText(size=5)], [sg.Text('土体内摩擦角标准差',size=30),sg.InputText(size=5)],[sg.Text('列车荷载等效土柱高度平均值',size=30),sg.InputText(size=5)],[sg.Text('列车荷载等效土柱高度标准差',size=30),sg.InputText(size=5)] ] layout3=[[sg.T("结果分析",text_color="red",font=10)], [sg.Output(size=(80,15),key="jieguo")], [sg.Button('计算'), sg.Button('关闭')] ] layout=[ [sg.Column(layout1),sg.Column(layout2)], [layout3] ] # 创造窗口 window = sg.Window('Window Title', layout,finalize=True) while True: event, values = window.read() if event == "计算" : a=values["a"] b=values["b"] appl=a/b print('-----------------失效概率抽样计算结果-------------') print("失效概率:",appl) if event == "关闭": break window.close()
07-17
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值