Text Justification_leetcode_go

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

思路:

  • 完成两件事,按组装填。是否还能再填一个空格,分两个case。分别处理组内空格。
  • curWordIdx := make([]int,0)用来修补空格很方便。
  • 用i遍历words,回退方便。
  • 最后一行左对齐的要求,特殊处理。(不添空格,直接返回)
  • 居中的实现:记录间隔的空格,将单词重新放入。拼接字串的方式不容易实现。
  • 细节:对某一个解。用数组要填充空格。用字串则不用。
  • 在循还体内处理最后一组,上下文变量多,代码好写。

解:

func fullJustify(words []string, maxWidth int) []string {
    res := make([]string,0)
    curOne := make([]byte,maxWidth)
    for idxCurOne:=0;idxCurOne<len(curOne);idxCurOne++{
        curOne[idxCurOne] = ' '
    }

    curIdx :=-1
    curWords := make([]string,0)

    for j:=0;j<len(words);j++{
        if curIdx+len(words[j]) < maxWidth-1{
            //默认加上空格,组内处理时再退回
            curWords = append(curWords,words[j])
            for chIdx:=0;chIdx<len(words[j]);chIdx++{
                curIdx++
                curOne[curIdx] = words[j][chIdx]
            }

            curIdx++
            curOne[curIdx] = ' '
            //最后一组,左对齐,留尾部的空格
            if j == len(words)-1{
                str := string(curOne)
                res = append(res,str)
                break
            }


        }else if curIdx+len(words[j]) == maxWidth-1{
            //一组正好加满
            for chIdx:=0;chIdx<len(words[j]);chIdx++{
                curIdx++
                curOne[curIdx] = words[j][chIdx]
            }
            res = append(res,string(curOne[0:curIdx+1]))
            curOne = make([]byte,maxWidth)
            for idxCurOne:=0;idxCurOne<len(curOne);idxCurOne++{
                curOne[idxCurOne] = ' '
            }
            curWords = make([]string,0)
            curIdx = -1
        }else{

            //仅有一个单词
            if len(curWords) == 1{
                res = append(res,string(curOne))
                curOne = make([]byte,maxWidth)
                for idxCurOne:=0;idxCurOne<len(curOne);idxCurOne++{
                    curOne[idxCurOne] = ' '
                }
                curWords = make([]string,0)
                curIdx = -1
                j--
                continue
            }

            //无法加单词,处理下一组
            if curOne[curIdx] == ' '{
                curIdx--
            }
            spaceNum := maxWidth-1-curIdx
            spaceInterval := make([]int,len(curWords)-1)
            for idx,_ := range spaceInterval{
                spaceInterval[idx] = 1
            }
            for k:=0;k<spaceNum;k++{
                idx:= k%len(spaceInterval)
                spaceInterval[idx]++
            }
            curOneS := ""
            for k:=0;k<len(spaceInterval);k++{
                curOneS+= curWords[k]
                for l:=0;l<spaceInterval[k];l++{
                    curOneS+= " "
                }
            }
            curOneS += curWords[len(curWords)-1]
            res = append(res,curOneS)

            curOne = make([]byte,maxWidth)
            for idxCurOne:=0;idxCurOne<len(curOne);idxCurOne++{
                curOne[idxCurOne] = ' '
            }
            curWords = make([]string,0)
            curIdx = -1
            j--
        }
    }
    return res
}

附上上次写的代码:

其它mark:Runtime: 0 ms, faster than 100.00% of Go online submissions for Text Justification.通过测试,但运动时间0ms???不知道是不是leetcode的bug。

func fullJustify(words []string, maxWidth int) []string {
    var res []string
    collect := make([]string, 0, len(words))
    collectLength := 0
    for i := 0; i < len(words); i++ {
        collectLengthMayBe := collectLength
        if collectLength == 0 {
            collectLengthMayBe += len(words[i])
        } else {
            collectLengthMayBe += len(words[i]) + 1
        }
        if collectLengthMayBe > maxWidth {
            //handle this group
            if len(collect) == 1 {
                resElem := collect[0]
                for i := 0; i<maxWidth-len(collect[0]);i++  {
                    resElem += " "
                }
                res = append(res, resElem)
            }else {
                //hasSpace
                var strSpace []string
                strSpace = make([]string, len(collect)-1, len(words))
                for i := 0; i < len(strSpace); i++ {
                    strSpace[i] = " "
                }
                leftSpace := maxWidth - collectLength
                for i := 0; leftSpace > 0; i = (i + 1) % len(strSpace) {
                    strSpace[i] += " "
                    leftSpace--
                }
                resElem := ""
                for i := 0; i < len(strSpace); i++ {
                    resElem = resElem + collect[i] + strSpace[i]
                }
                resElem += collect[len(collect)-1]
                res = append(res, resElem)
            }
            //reset
            collect = make([]string, 0, len(words))
            collect = append(collect, words[i])
            collectLength = len(words[i])
            continue
        }
        collectLength = collectLengthMayBe
        collect = append(collect, words[i])
    }

    //handle the last group
    if len(collect) == 1 {
        resElem := collect[0]
        for i := 0; i<maxWidth-len(collect[0]);i++  {
            resElem += " "
        }
        res = append(res, resElem)
        return res
    }

    //left-justified
    resElem := ""
    for i := 0; i < len(collect)-1; i++ {
        resElem = resElem + collect[i] + " "
    }
    resElem += collect[len(collect)-1]
    //resElem长度是变化的,要先取了来,不能写在循环中
    spaceNum :=maxWidth-len(resElem)
    for i := 0; i < spaceNum; i++ {
        resElem = resElem + " "
    }
    res = append(res, resElem)

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

推荐阅读更多精彩内容