C++实现LeetCode(68.文本左右对齐)

[LeetCode] 68.Text Justification 文本左右对齐

Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth 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 maxWidthcharacters.

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 extraspace is inserted between words.

Note:

  • A word is defined as a character sequence consisting of non-space characters only.
  • Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.
  • The input array words contains at least one word.

Example 1:

Input:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
Output:
[
"This    is    an",
"example  of text",
"justification.  "
]

Example 2:

Input:
words = ["What","must","be","acknowledgment","shall","be"]
maxWidth = 16
Output:
[
"What   must   be",
"acknowledgment  ",
"shall be        "
]
Explanation: Note that the last line is "shall be    " instead of "shall     be",
because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified becase it contains only one word.

Example 3:

Input:
words = ["Science","is","what","we","understand","well","enough","to","explain",
"to","a","computer.","Art","is","everything","else","we","do"]
maxWidth = 20
Output:
[
"Science  is  what we",
"understand      well",
"enough to explain to",
"a  computer.  Art is",
"everything  else  we",
"do                  "
]

我将这道题翻译为文本的左右对齐是因为这道题像极了word软件里面的文本左右对齐功能,这道题我前前后后折腾了快四个小时终于通过了OJ,完成了之后想着去网上搜搜看有没有更简单的方法,搜了一圈发现都差不多,都挺复杂的,于是乎就按自己的思路来说吧,由于返回的结果是多行的,所以我们在处理的时候也要一行一行的来处理,首先要做的就是确定每一行能放下的单词数,这个不难,就是比较n个单词的长度和加上n - 1个空格的长度跟给定的长度L来比较即可,找到了一行能放下的单词个数,然后计算出这一行存在的空格的个数,是用给定的长度L减去这一行所有单词的长度和。得到了空格的个数之后,就要在每个单词后面插入这些空格,这里有两种情况,比如某一行有两个单词"to" 和 "a",给定长度L为6,如果这行不是最后一行,那么应该输出"to   a",如果是最后一行,则应该输出 "to a  ",所以这里需要分情况讨论,最后一行的处理方法和其他行之间略有不同。最后一个难点就是,如果一行有三个单词,这时候中间有两个空,如果空格数不是2的倍数,那么左边的空间里要比右边的空间里多加入一个空格,那么我们只需要用总的空格数除以空间个数,能除尽最好,说明能平均分配,除不尽的话就多加个空格放在左边的空间里,以此类推,具体实现过程还是看代码吧:

class Solution {
public:
    vector<string> fullJustify(vector<string> &words, int L) {
        vector<string> res;
        int i = 0;
        while (i < words.size()) {
            int j = i, len = 0;
            while (j < words.size() && len + words[j].size() + j - i <= L) {
                len += words[j++].size();
            }
            string out;
            int space = L - len;
            for (int k = i; k < j; ++k) {
                out += words[k];
                if (space > 0) {
                    int tmp;
                    if (j == words.size()) {
                        if (j - k == 1) tmp = space;
                        else tmp = 1;
                    } else {
                        if (j - k - 1 > 0) {
                            if (space % (j - k - 1) == 0) tmp = space / (j - k - 1);
                            else tmp = space / (j - k - 1) + 1;
                        } else tmp = space;
                    }
                    out.append(tmp, ' ');
                    space -= tmp;
                }
            }
            res.push_back(out);
            i = j;
        }
        return res;
    }
};

到此这篇关于C++实现LeetCode(68.文本左右对齐)的文章就介绍到这了,更多相关C++实现文本左右对齐内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • C++实现LeetCode(64.最小路径和)

    [LeetCode] 64. Minimum Path Sum 最小路径和 Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in t

  • C++实现LeetCode(189.旋转数组)

    [LeetCode] 189. Rotate Array 旋转数组 Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: [1,2,3,4,5,6,7] and k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate

  • C++实现LeetCode(62.不同的路径)

    [LeetCode] 62. Unique Paths 不同的路径 A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner

  • C++实现LeetCode(63.不同的路径之二)

    [LeetCode] 63. Unique Paths II 不同的路径之二 A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right c

  • C++实现LeetCode(60.序列排序)

    [LeetCode] 60. Permutation Sequence 序列排序 The set [1,2,3,...,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3: "123" "132" "213" &

  • C++实现LeetCode(59.螺旋矩阵之二)

    [LeetCode] 59. Spiral Matrix II 螺旋矩阵之二 Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. Example: Input: 3 Output: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] 此题跟之前那道 Spiral Matrix 本质上没什么区别,就相当于个类似逆

  • C++实现LeetCode(70.爬楼梯问题)

    [LeetCode] 70. Climbing Stairs 爬楼梯问题 You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive integer. Examp

  • C++实现LeetCode(61.旋转链表)

    [LeetCode] 61. Rotate List 旋转链表 Given the head of a linked list, rotate the list to the right by k places. Example 1: Input: head = [1,2,3,4,5], k = 2 Output: [4,5,1,2,3] Example 2: Input: head = [0,1,2], k = 4 Output: [2,0,1] Constraints: The number

  • C++实现LeetCode(68.文本左右对齐)

    [LeetCode] 68.Text Justification 文本左右对齐 Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that i

  • text-align:justify实现文本两端对齐 兼容IE

    对于text-align 我们再熟悉不过了,可是它有个justify属性,平时很少用到,就鲜为人知了.justify是一种文本靠两边布局方式,一般应用于书刊杂志排版:合理运用text-align:justify 有时会省去很多开发的时间. 要想更好的理解 css, 尤其是 IE 下对 css 的渲染,haslayout 是一个非常有必要彻底弄清楚的概念.大多 IE 下的显示错误,就是源于 haslayout. 什么是 haslayout ? haslayout 是Windows Internet

  • 输出的文本实现对齐的方法(超简单)

    在本博客中,可以找到一篇<c#实现输出的字符靠右对齐的示例> 它有教大家怎样实现字符串输出进行左齐或者是右对齐. 本篇的方法,超简单,是使用string.Format()对本进行格式化输出即可. Source Code class Ad { private string[] myVar; public Ad(string[] myValue) { this.myVar = myValue; } public void PadLeft() { foreach (string s in this.

  • 文本左右对齐排版的批处理

    如1.txt内容如下.复制内容到剪贴板代码: 111111111111111111111 98912 张三 222222222222222222 150020 李四四 333333333333333333333 360000 王五 444444444444444444 2332 赵六六 555555555555555555 222 田七 666666666666666666666 999999 舞吧通过批处理输出为:复制内容到剪贴板代码: 111111111111111111111 98912

  • WML学习之三 显示文本

    显示文本 在文本的显示上WML基本和HTML相同.文字段落包含在<p align= "alignment" mode=" wrapmode">和</p>之间,align属性指定该段文字的对齐方式,默认的是left,其他可选择right和center:mode属性指定当一行显示不下所有的文字时是否自动换行,默认的是自动换行wrap,如果选nowrap,则在一行中显示,浏览器会通过类似于水平滚动条的机制来显示所有文字.  换行标签也一样为<

  • iOS开发实战之Label全方位对齐的轻松实现

    前言 本文主要给大家介绍了关于iOS Label全方位对齐的实现方法,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧 ARUILabelTextAlign 1. 实现 UILabel文本在 左(上 中 下).中(上 中 下).右(上 中 下) 9个方位显示: 2. 提供富文本底部不对齐的解决方案: 演示 核心代码: ARAlignLabel.h #import <UIKit/UIKit.h> @class ARMaker; typedef NS_ENUM(NSUInteger,

  • wxPython实现文本框基础组件

    本文实例为大家分享了wxPython实现文本框的具体代码,供大家参考,具体内容如下 #-*- coding:utf-8 -*- """ ############################################# StaticText 参数说明 --即 label parent: -- 父窗口部件. id: -- 标识符.使用-1可以自动创建一个唯一的标识. label: -- 你想显示在静态控件中的文本. pos: -- 一个wx.Point或一个Python

  • HTML技巧汇编

    1.怎样定义网页语言(字符集)?            在制作网页过程中,你首先要定义网页语言,以便访问者浏览器自动设置语言,而我们用所见即所得的HTML工具时,都没有注意到这个问题,因为它是默认设置.要设置的语言可以在HTML代码状态下找到: <meta http-equiv="Content Type" content="text/html; charset=gb2312"> 把charset=gb2312改换成其它语言代码即可,比如英文harset

  • Lesson01_07 图像标签

    <IMG>标签格式:<IMG SRC="">属性: ALT (指定鼠标移动到图像上或是没有显示图像时显示的文本)代码: <IMG src="http://www.thinkme.cn/logo/blog1.gif" alt=Loncer.blog>效果: ALIGN (指定图像与周围的文本的对齐方式) 代码: aaaa<IMG src="http://www.thinkme.cn/logo/blog1.gif AL

  • Log4j_配置方法(全面讲解)

    一.Log4j简介 Log4j有三个主要的组件:Loggers(记录器),Appenders (输出源)和Layouts(布局).这里可简单理解为日志类别,日志要输出的地方和日志以何种形式输出.综合使用这三个组件可以轻松地记录信息的类型和级别,并可以在运行时控制日志输出的样式和位置. 1.Loggers Loggers组件在此系统中被分为五个级别:DEBUG.INFO.WARN.ERROR和FATAL.这五个级别是有顺序的,DEBUG < INFO < WARN < ERROR <

随机推荐