题目
题目来自leetcode
- 有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!!";
}
}