You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode Text Justification问题:最后一行末尾多余空格去除求助

LeetCode文本对齐问题末尾空格修复方案

我在解决LeetCode的**Text Justification(文本对齐)**问题时,已经通过29个测试用例中的24个,但在以下测试用例中出现问题:

测试用例输入:
["ask","not","what","your","country","can","do","for","you", "ask","what","you","can","do","for","your","country"]
我的输出:
["ask not what","your country can","do for you ask", "what you can do","for your country "]
预期输出:
["ask not what","your country can","do for you ask", "what you can do","for your country"]

核心问题:当最后一行单词用单个空格分隔后,总长度恰好等于题目给定的字符长度限制时,末尾会多出一个空格,怎么解决?我试了各种方法都没搞定,以下是我的代码:

from typing import List

class Solution:
    def full_justify(self, w: List[str], m: int) -> List[str]:
        a = []
        t = []
        i = 0

        while i < len(w):
            n = m

            while i < len(w) and n >= len(w[i]) + len(t):
                n -= len(w[i])
                t.append(w[i])
                i += 1

            lenc = sum(len(s) for s in t)

            if i < len(w) and len(t) > 1:
                spaces = (m - lenc) // (len(t) - 1)
                extra_spaces = (m - lenc) % (len(t) - 1)
                line = t[0]

                for j in range(1, len(t)):
                    spaces_to_add = spaces + (1 if j <= extra_spaces else 0)
                    line += ' ' * spaces_to_add + t[j]

                a.append(line)    
            else:
                line = ' '.join(t) + ' ' * (m - lenc)

                if len(line) > m and line[-1] == ' ':
                    line = line[:-1]

                a.append(line)     
   
            t.clear()
        return a

问题出在哪

你处理最后一行时,空格数算错了。' '.join(t)已经在单词之间加了单个空格,这时候该行的总长度是lenc + (len(t)-1)(每个间隙一个空格),但你还是用m - lenc来计算要补的空格,这就多补了len(t)-1个空格。最后判断len(line) > m时,当刚好凑够长度,这个条件不成立,末尾的空格就留下来了。

怎么改

直接调整最后一行的处理逻辑:

else:
    # 最后一行左对齐,单词间单个空格,长度不够才补空格,够了就不补
    line = ' '.join(t)
    if len(line) < m:
        line += ' ' * (m - len(line))
    a.append(line)

或者用Python内置的ljust方法更简洁:

else:
    line = ' '.join(t).ljust(m)
    a.append(line)

ljust会自动把字符串左对齐,长度不足时在末尾补空格到指定长度,刚好够的话就不会补,完美符合要求。

修复后的完整代码

from typing import List

class Solution:
    def full_justify(self, words: List[str], maxWidth: int) -> List[str]:
        result = []
        current_line = []
        i = 0

        while i < len(words):
            remaining_width = maxWidth

            # 往当前行添加尽可能多的单词
            while i < len(words) and remaining_width >= len(words[i]) + len(current_line):
                remaining_width -= len(words[i])
                current_line.append(words[i])
                i += 1

            total_word_length = sum(len(word) for word in current_line)

            # 非最后一行且单词数大于1,均匀分配空格
            if i < len(words) and len(current_line) > 1:
                spaces_between = (maxWidth - total_word_length) // (len(current_line) - 1)
                extra_spaces = (maxWidth - total_word_length) % (len(current_line) - 1)
                line = current_line[0]

                for j in range(1, len(current_line)):
                    spaces = spaces_between + (1 if j <= extra_spaces else 0)
                    line += ' ' * spaces + current_line[j]

                result.append(line)
            else:
                # 最后一行或单个单词,左对齐处理
                line = ' '.join(current_line).ljust(maxWidth)
                result.append(line)

            current_line.clear()
        return result

内容的提问来源于stack exchange,提问作者coderakbar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 19:50:56