Text Justification 文本左右对齐
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 Lcharacters.
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.
- A line other than the last line might contain only one word. What should you do in this case?
In this case, that line should be left-justified.
class Solution { public: vector<string> fullJustify(vector<string> &words, int L){ vector<string> result; // input validation if(words.empty()) return result; // param @ i 遍历单词的下标临时变量 // param @ k 校正后每行单词个数 // param @ l 每行字符(除空格)个数 // 每次遍历构造一行 将单词检索进新数组 for(int i = 0, k, l; i < words.size(); i += k){ // 查询单词不能越界 并且每行增添的单词需要满足要满足中间能插入空格 // for(k = 0, l = 0; k+i < words.size() && l + words[i+k].size()<= L-k; l += words[i+k].size(), ++k); // 构造新行 string temp = words[i]; // 每行首单词 for(int j = 0; j < k-1; ++j){ int blanks = (L-l)/(k-1) + (j < (L-l)%(k-1)); // 已经是最后一行单词,要求左对齐,每个单词之间一个空格,剩下空格放在最后 if(i+k >= words.size()){ temp += " "; } else temp += string(blanks, ' '); temp += words[i+j+1]; } // 补全空格 temp += string(L-temp.size(), ' '); result.push_back(temp); } return result; } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2017-09-11 make_pair
2017-09-11 fwrite和fread函数的用法小结(转)
2017-09-11 函数fseek() 用法(转)
2015-09-11 表示数值的字符串