【作业】文本左右对齐

题目

题目来自leetcode

  1. 有N个单词的句子,要求每行限制在M个字符中显示,最左单词要向左对齐,最右单词向右对齐,空格要求平均分,不能时最左边的显示最多的空格

结论

输入:
“This”, “is”, “a”, “max”,
“word”, “line”, “test”, “,”,
“which”, “is”, “a”, “test”,
“of”,“leetcode”
在这里插入图片描述

代码

#pragma

#include <vector>
#include <iostream>
#include <string>
#include <sstream>
#include <optional>

using StrLst = std::vector<std::string>;

std::optional<std::string> get_max_width_line(const StrLst& lst, const int max_width) {
	std::stringstream strstr;
	StrLst::const_iterator cur = lst.begin();
	while (cur!=lst.end()) {
		int cur_width = 0;
		StrLst::const_iterator start = cur;
		for (; cur != lst.end(); ++cur) {
			cur_width += cur->size();
			if (cur_width > max_width)
				break;
			++cur_width; // add the blank
		}
		if (cur == start) {
			return std::optional<std::string>();
		}
		int words_width = 0;
		int words_count = 0;
		for (auto it = start; it != cur; ++it) {
			words_width += it->size();
			++words_count;
		}

		if (words_count > 1) {
			int each_bw = 0;
			int blank_width = max_width - words_width;
			int left_blank_width = blank_width;
			--words_count;
			each_bw = blank_width / words_count;
			auto end_word_it = start + words_count;
			strstr << *start;
			for (int i = 0; i < blank_width - each_bw * words_count; ++i)
				strstr << ' ';
			++start;
			for (; start != cur; ++start) {
				for (int i = 0; i < each_bw; ++i) {
					strstr << ' ';
				}
				strstr << *start;
				left_blank_width -= each_bw;
			}
		}
		else {
			strstr << *start;
		}
		strstr << std::endl;
	}
	return strstr.str();
}

void test_max_width_words(){
	StrLst strlst = {
		"This", "is", "a", "max",
		"word", "line", "test", ",",
		"which", "is", "a", "test", 
		"of","leetcode"
	};

	auto res = get_max_width_line(strlst, 15);
	if (res.has_value()) {
		std::cout << "Res is: " << std::endl << res.value();
	}
	else {
		std::cout << "There is no result!!";
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值