Example: Input: words = ["This", "is", "an", "example", "of", "text", "justification."] maxWidth = 16 Output: [ "This is an", "example of text", "justification. " ]
这个问题可以分为两个不同的部分。
在第一部分中,我们需要检查一行中可以容纳多少个单词。
在第二部分中,确定要在这些行之间平均插入的空间。为此,计算要引入的空格数,然后除以单词数。
需要考虑的一些极端情况:
- 每个单词之间至少应有一个空格。
- 如果一行只有一个单词,则应保持对齐。
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+章 |