`

LeetCode 68 - 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.

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.
public List<String> fullJustify(String[] words, int L) {
    List<String> list = new ArrayList<>();
    int n = words.length;
    char[] spaces = new char[L];
    Arrays.fill(spaces, ' ');
    for(int i=0; i<n; i++) {
        int j = i; 
        int len = words[i].length();
        while(i<n-1 && len+1+words[i+1].length()<=L) {
            len += 1+words[++i].length();
        }
        //只有一个word或者是最后一行的时候,需要左对齐
        boolean left = (j==i || i==n-1);
        int avg = left ? 0 : (L-len) / (i-j); //平均空格个数-1
        int rem = left ? 0 : (L-len) % (i-j); //平均之后多出来的空格个数
        StringBuilder sb = new StringBuilder(words[j]);
        while(j < i) {
            sb.append(spaces, 0, avg+1);
            if(rem-- > 0) sb.append(' ');
            sb.append(words[++j]);
        }
        sb.append(spaces, 0, L-sb.length());
        list.add(sb.toString());
    }
    return list;
}

 

重构了一下Java代码:

public List<String> fullJustify(String[] words, int L) {
    List<String> res = new ArrayList<>();
    int n = words.length;
    char[] spaces = new char[L];
    Arrays.fill(spaces, ' ');
    for(int i=0; i<n; i++) {
        int len = words[i].length();
        int j = i;
        while(i<n-1 && len+1+words[i+1].length()<=L) {
            len += 1+words[++i].length();
        }
        StringBuilder sb = new StringBuilder(words[j]);
        if(j == i || i==n-1) {
            while(i==n-1 && j < i) {
                sb.append(" "+words[++j]);
            }
            sb.append(spaces, 0, L-sb.length());
        } else {
            int avg = (L-len)/(i-j);
            int rem = (L-len)%(i-j);
            while(j < i) {
                sb.append(spaces, 0, avg+1);
                if(rem-- > 0) sb.append(" ");
                sb.append(words[++j]);
            }
        }
        res.add(sb.toString());
    }
    return res;
}

 

C++的代码:

vector<string> fullJustify(vector<string>& words, int maxWidth) {
    vector<string> result;
    int i = 0, n = words.size();
    while(i < n) {
        int j(i), cnt(0), len(0);
        while(i<n && len+cnt+words[i].size()<=maxWidth) {
            len += words[i++].size();
            cnt++;
        }
        bool left = (cnt==1 || i==n); // should be left aligned or not
        int space = left ? 1 : (maxWidth-len) / (cnt-1);
        int rem   = left ? 0 : (maxWidth-len) % (cnt-1);
        string s;
        while(j < i) {
            s.append(words[j++]);
            if(j < i)
                s.append(space, ' ');
            if(rem > 0) {
                s.append(1, ' ');
                rem--;
            }
        }
        if(s.size() < maxWidth) {
            s.append(maxWidth-s.size(), ' ');
        }
        result.push_back(s);
    }
    return result;
}

 

分享到:
评论

相关推荐

    LeetCode 101 - A LeetCode Grinding Guide (C++ Version).rar

    《LeetCode 101 - A LeetCode Grinding Guide (C++ Version)》是一本专为C++程序员设计的深入解析LeetCode算法问题的指南。这本书采用彩色版,以直观的方式讲解了各种数据结构和算法,旨在帮助读者磨练编程技能,...

    LeetCode 101 - A LeetCode Grinding Guide (C Version).pdf

    《LeetCode 101 - A LeetCode Grinding Guide (C++ Version)》是一本面向有一定C++编程基础,但缺乏刷题经验读者的教科书和工具书。作者高畅(Chang Gao)基于其在准备实习和秋招过程中对LeetCode题目的整理和刷题...

    C语言-leetcode题解之68-text-justification.c

    今天我们将要探讨的文件标题"C语言-leetcode题解之68-text-justification.c",实际上是一份针对leetcode网站上第68题“文本对齐”问题的C语言解决方案。 此问题的具体要求是,给定一个单词列表和一个长度限制,编写...

    js-leetcode题解之68-text-justification.js

    LeetCode 题号 68 的题目是 "Text Justification"(文本对齐)。这个题目的目标是在给定的单词数组和最大宽度的情况下,将这些单词进行合理地排列,使得每一行都能够达到最大的宽度,并且左右对齐。这道题目要求输出...

    LeetCode---C++实现

    《LeetCode---C++实现》是一本专注于C++编程语言解决LeetCode在线判题平台上的算法问题的书籍。LeetCode是程序员广泛使用的平台,它提供了大量的编程题目来提升编程技能和算法理解,尤其对于准备面试的程序员来说,...

    leetcode1-240题中文题解,md格式,java

    1. leetCode-126-Word-LadderII.md:这涉及到第126题,词梯问题,通常是一个字符串转换问题,目标是找到两个单词之间的最短转换序列,每次只改变一个字母。 2. leetcode-224-Basic-Calculator.md:这是第224题,基础...

    leetcode-leetcode-cli-plugins:leetcode-cli的第3方插件

    leetcode-cli-plugins leetcode-cli 的第 3 方插件。 什么是 如何使用 如何使用 插件 名称 描述 增强的命令 按公司或标签过滤问题 list 不要在同一台计算机上使 Chrome 的会话过期 login 不要在同一台计算机上使 ...

    离线和leetcode-leetcode-cn-cli:为leetcode-cn.com工作

    leetcode-cli 一个享受 leetcode 的高效 cli 工具! 非常感谢 leetcode.com,一个非常棒的网站! ⦙⦙⦙⦙⦙⦙⦙⦙ 一个很打问题的方法。 问题来缓解离线思考。 编码前的源代码。 居住和与 leetcode.com。 下载你...

    leetcode2sumc-leetcode-cli:leetcode-cli

    leetcode-cli 注意:这个存储库是为了临时使用而分叉的。 注意:从 webbrowser 复制 cookie 并使用leetcode user -c可以临时修复不能。 一个享受 leetcode 的高效 cli 工具! 非常感谢 leetcode.com,一个非常棒的...

    leetcode答案-leetcode--python:leetcode--python

    这个压缩包“leetcode--python”显然包含了与LeetCode相关的Python解题代码,可能是一个开源项目,用于存储用户或社区成员解决LeetCode问题的Python实现。 **LeetCode概述** LeetCode提供了一系列的算法和数据结构...

    leetcode26-algo:算法与数据结构

    leetcode26 algo 算法与数据结构,练习代码 语言:java 8 开发工具:vscode,安装插件Java Extension Pack vscode有智能提示,可调试,有重构支持,满足代码练习要求,相比IDEA更轻量级,普通笔记本即可流畅运行。 ...

    leetcode答案-Leetcode--Algo:Leetcode-某事

    leetcode 答案Leetcode---算法 我对 Leetcode 算法问题的回答

    leetcode接口-leetcodeHelper:leetcodeHelper

    leetcode 接口 该项目可帮助您使用首选的 IDE 或带有命令行界面 (CLI) 的编辑器来执行 leetcode。 入门 先决条件 Windows 10、MacOS、Linux Chrome版 &gt;=90.0.4430 安装 # Prepare your virtual environment conda ...

    leetcode答案-leetcode-machine-swift:Xcode中的leetcode解决方案验证

    leetcode-machine-swift :SOS_button: 请帮助在Sources/leetcode-machine-swift/leetcode.swift设置所有 leetcode 问题。 :SOS_button: 在 swift 编码时有 xcode 总是好的。 利用自动补全、类型检查...功能可以帮助...

    离线和leetcode-leetcode-cli-2.6.1:leetcode-cli-2.6.1

    leetcode-cli 一个享受 leetcode 的高效 cli 工具! 非常感谢 leetcode.com,一个非常棒的网站! ⦙⦙⦙⦙⦙⦙⦙⦙ 一个很打问题的方法。 问题来缓解离线思考。 编码前的源代码。 居住和与 leetcode.com。 下载你...

    leetcode2-leetcode-training:算法训练

    leetcode-训练 算法训练。 java $: javac hello.java java $: java hello c $: gcc hello.c 如果没有错误会生成a.out 可执行文件 c $: ./a.out leetcode cli leetcode version leetcode help leetcode help user ...

    zwangZJU#LeetCode-in-python-wznote#LeetCode-python-739-每日温度1

    解题思路思路和LeetCode-python 503.下一个更大元素 II一致,只是这里求的是下标的距离,而不是数值倒序搜索,用到栈,栈里存储索引情况1:若栈为

    leetcode2-21-DAYS-PROGRAMMING-CHALLENGE-ACES:编码CP,探索新事物

    leetcode 2 21 天-编程-挑战-ACES CP、探索新事物、Web 开发 第一天: 解决了 leetcode 问题 - 10 月 4 日 解决 codechef 十月挑战问题 写了一些关于 GFG 的文章 第 2 天: 解决了 leetcode 问题 - 10 月 5 日和 6 ...

    leetcode中国-leetcode-rust-cn:用Rust刷LeetCode,带中文注释

    leetcode-rust-cn LeetCode solutions in Rust, with Chinese comment. 用 Rust 刷 LeetCode,带中文注释 VSCode 插件 ,插件用法见其 插件 插件 切换到 LeetCode 英文版,然后通过第三方帐号(如 GitHub)登录 用法:...

    LeetCode--Linked List.cpp

    文件中包含了LeetCode中Tag为LinkedList的题目参考代码。

Global site tag (gtag.js) - Google Analytics