Text Justification

本文介绍了一种用于文本排版的算法,确保每行文本恰好达到指定长度,同时保持左右对齐。讨论了不同情况下的处理策略,包括一行只有一个单词、最后一行的左对齐以及普通行的均匀分布空格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Corner Cases:

 

  • 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.
 这题主要是对单词进行按行排序.主要要考虑的情况有三种:
1.提示中提醒的,一行只有一个单词,则放置在左边,left-justified.
2.最后一行,即使有多个单词,也是放置在左边,left-justified,多个单词时,之间只有一个空格.
3.不是最后一行,但是间隔无法整除时,左边要比右边间隔大,但是要尽量均分,即只能相差一个.
代码如下:
class Solution(object):
    def fullJustify(self, words, maxWidth):
        """
        :type words: List[str]
        :type maxWidth: int
        :rtype: List[str]
        """
        #slice the words in a sequential way, don't understand the last line meaning 
        if not words:
            return []
        res = []
        n = len(words)
        start = 0
        while start < n:
            lengthSum = 0
            cnt = 0
            while start+cnt < n and  lengthSum + len(words[start+cnt]) + cnt <=  maxWidth: #frist test whether can add the word, then add the word in the line
                lengthSum += len(words[start+cnt])
                cnt += 1
            #make the line
            if cnt == 1:
                res.append(words[start]+(maxWidth-lengthSum)*" ")
            elif start + cnt == n:  #the last line, several words together, left justify
                cur = " ".join(words[start: start+cnt])
                if len(cur) < maxWidth:
                    cur+= " "*(maxWidth-len(cur))
                res.append(cur)
            else: #common line
                avg = (maxWidth - lengthSum)/(cnt-1)
                if (maxWidth - lengthSum)%(cnt-1) == 0:
                    res.append((" "*avg).join(words[start:start+cnt]))
                else:
                    n1 = maxWidth - lengthSum - avg*(cnt-1) + 1#number of left slots has more space
                    n2 = avg - (cnt-1)
                    cur =(" "*(avg+1)).join(words[start:start+n1])
                    cur += " "*avg
                    cur += (" "*avg).join(words[start+n1:start+cnt])
                    res.append(cur)
            start += cnt

        return res

 参考leetcode精简思路,找长度一样,主要是生成行的时候简单:

vector<string> fullJustify(vector<string> &words, int L) {
    vector<string> res;
    for(int i = 0, k, l; i < words.size(); i += k) {
        for(k = l = 0; i + k < words.size() and l + words[i+k].size() <= L - k; k++) {
            l += words[i+k].size();
        }
        string tmp = words[i];
        for(int j = 0; j < k - 1; j++) {
            if(i + k >= words.size()) tmp += " ";
            else tmp += string((L - l) / (k - 1) + (j < (L - l) % (k - 1)), ' ');
            tmp += words[i+j+1];
        }
        tmp += string(L - tmp.size(), ' ');
        res.push_back(tmp);
    }
    return res;
}

 

 

转载于:https://www.cnblogs.com/sherylwang/p/5862922.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值