6.27 - hard - 16

68. Text Justification

這題其實(shí)也怪怪的,這種題目怎么能算在難題行列呢?解題的想法就是先把每一個(gè)row的詞找出來,然后再分配空格,最后一行要特殊處理

class Solution(object):
    def fullJustify(self, words, maxWidth):
        """
        :type words: List[str]
        :type maxWidth: int
        :rtype: List[str]
        """
        index = 0
        cur_length = 0
        row = []
        res = []
        while index < len(words):
            if len(words[index]) + cur_length <= maxWidth:
                row.append(words[index])
                cur_length += len(words[index]) + 1
                index += 1
            else:
                # process row
                self.process(row, maxWidth, res)
                # reset row
                row = []
                cur_length = 0
        if row:
            cur_length = 0
            l = ""
            for word in row:
                l += word + " "
            if len(l) <= maxWidth:
                res.append(l+(maxWidth-len(l))*" ")
            else:
                res.append(l[:-1])
        return res

    def process(self, row, maxWidth, res):
        spaces = maxWidth - len("".join(row))
        if len(row) == 1:
            res.append(row[0]+spaces*" ")
        else:
            space_list = [0 for _ in range(len(row)-1)]
            i = 0
            while spaces:
                space_list[i] += 1
                spaces -= 1
                i += 1
                i %= len(space_list)
            
            line = ""
            for i in range(len(row)-1):
                line += row[i] + space_list[i]*" "
            res.append(line+row[-1])
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,921評(píng)論 0 33
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,692評(píng)論 18 399
  • 花開無聲,花謝有聲。 和人的一生正好相反, 人出生時(shí)總會(huì)伴著哇哇大哭的聲音, 但人在離開時(shí),往往會(huì)悄然無聲。
    喜兒的小日子閱讀 446評(píng)論 0 5
  • 這張照片,傳遍了今天文山州的朋友圈。無論男女老少,從事各種職業(yè),都有人轉(zhuǎn)發(fā)。 這張照片,有一位老母親和她的...
    寧歌911閱讀 265評(píng)論 0 0
  • 那個(gè)春天的夜晚,櫻花園的香氣彌漫了整個(gè)校園,月光也顯得格外皎潔。那個(gè)男孩鼓起十足的勇氣,抱著那封不知道被自己改過多...
    989bfd732fe3閱讀 265評(píng)論 0 3

友情鏈接更多精彩內(nèi)容