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 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.
click to show corner cases.
文本对齐

【解题思路】关键在于如何计算每行的单词数量和空格。

【考查内容】字符串

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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值