【算法】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 maxWidth 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.

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                  "
]

给出一组单词 words ,一个长度 maxWidth ,返回一个字符串数组满足如下条件:

  1. 所有字符长度均为 maxWidth
  2. 单词不可切割
  3. 每行字符串中,每个单词之间的空格大于等于 1 ,且均等分
  4. 如无法均等分,则左边的空格数比右边的多
  5. 最后一行单词之间只有一个空格,剩余空间用空格补齐

解题思路

主要就是计算每行字符串所需的单词 索引范围空格数量 ,最后一行的处理也有些不同:

  1. 动态字符串长度 strCount,头位置 from ,尾位置 to,单词个数 wordCount = to - from + 1
  2. 判断条件就是 strCount + (当前单词长度)word.count + wordCount - 1 > mixWidth 时,from ~ to-1 就是符合条件的单词索引范围
  3. from ~ to-1 单词数量判断空格区间有几个:
    • 单词数量<3时有一个,空格长度为 maxWidth - word.count,添加到单词后面
    • 单词数量>3时有 单词数量 - 1 个
    • 较大空格数量 larCount = (maxWidth - wordsLen) % (wordsCount - 1)
    • 空格长度 spaceLen = (maxWidth - wordsLen) / (wordsCount - 1)
    • 头 larCount 个空格区域有 spaceLen+1,之后都是 spaceLen 个空格
    • 最后一个单词后面注意不添加空格
  4. 最后一行单词和空格交叉添加,最后位数不足用空格补齐

代码实现

Runtime: 8 ~ 20 ms
Memory: 21 MB

func fullJustify(_ words: [String], _ maxWidth: Int) -> [String] {
        //添加字符串的数组
        var result = [String]()
        //动态字符串长度 strCount,头位置 from 尾位置to
        var strCount = 0, from = 0, to = 0
        //循环条件,to 在 words 范围内
        while to < words.count {
            // 空格数 spaceCount = to - from
            // 字符数 + spaceCount > maxWidth , 或者 to 不在 words 范围中时,跳出循环,
            while to < words.count && strCount + words[to].count + to - from <= maxWidth {
                //循环条件内,添加动态字符串长度
                strCount += words[to].count
                //to 后移一位
                to += 1;
            }
            // to 指向最后一个单词,应该跳出循环处理最后一行字符串
            if to == words.count {
                break
            }
            // from ~ to-1 的单词加上空格数满足条件,进行处理
            let strEl = self.fillSpace(words, maxWidth: maxWidth, from: from, to: to - 1, wordsLen: strCount)
            //将处理后的字符串添加进 result 中
            result.append(strEl)
            // 将 from 指向 to
            from = to
            // 重置 strCount 为 0
            strCount = 0
        }
        //处理最后一行字符串
        let strEl = self.fillLastLine(words, maxWidth: maxWidth, from: from, to: to - 1, wordsLen: strCount)
        result.append(strEl)
        //返回结果
        return result
    }

    func fillSpace(_ words: [String], maxWidth: Int, from: Int, to: Int, wordsLen: Int) -> String{
        var resStr = ""
        let space = "*"
        //单词数量 wordsCount
        let wordsCount = to - from + 1
        //较大空格的数量 larCount
        var larCount = 0
        //空格的长度 spaceLen
        var spaceLen : Int = 1
        if wordsCount<3 {
            //单词数量小于3时,larCount=0,spaceLen=maxWidth - wordsLen
            spaceLen = maxWidth - wordsLen
        }else{
            //单词数量大于等于3时,计算 larCount ,spaceLen
            larCount = (maxWidth - wordsLen) % (wordsCount - 1)
            spaceLen = (maxWidth - wordsLen) / (wordsCount - 1)
        }
        //from ~ to 单词加空格赋值给 resStr
        for idx in from ... to {
            resStr += words[idx]
            var spaceLen1 = spaceLen
            if larCount>0 {
                //若 larCount大于0,索命本次空格数量为 spaceLen + 1
                spaceLen1 += 1
                // larCount - 1
                larCount -= 1
            }
            //若不是最后一个单词,且并非只有一个单词时,添加空额
            //若是最后一个单词,且只有一个单词时,添加空格
            if (idx != to && wordsCount != 1) || (idx == to && wordsCount == 1)  {
                for _ in 0 ..< spaceLen1 {
                    resStr += space
                }
            }
        }
        //返回结果
        return resStr
    }
    func fillLastLine(_ words: [String], maxWidth: Int, from: Int, to: Int, wordsLen: Int) -> String {
        var resStr = ""
        let space = "*"
        //如果 from 小于 to
        if from < to {
            // from ~ to-1 单词和空格 加值到 resStr
            for idx in from ..< to {
                resStr += words[idx] + space
            }
        }
        // resStr 加最后一个单词
        resStr += words[to]
        //剩余空间用空格补齐
        let starNum = maxWidth - resStr.count
        for _ in 0 ..< starNum {
            resStr += space
        }
        //返回结果
        return resStr
    }

代码地址:https://github.com/sinianshou/EGSwiftLearning

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容