骨骼清奇Fit words

Catalog:
LC 68 Text Justification
[GoogleCall] LC 418 Sentence Screen Fitting

LC 68 Text Justification

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

"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" was just a really long and awkward way to say round robin. The following line implements the round robin logic:

for i in range(maxWidth - num_of_letters):
                cur[i%(len(cur)-1 or 1)] += ' '

Once you determine that there are only k words that can fit on a given line, you know what the total length of those words is num_of_letters. Then the rest are spaces, and there are (maxWidth - num_of_letters) of spaces. The "or 1" part is for dealing with the edge case len(cur) == 1.

So there are i spaces to allocation to k words, we keeping allocating from the left, when there are more paces than k, say 5 spaces and 4 words, spaces will be allocated at index 0, 1, 2, 3, 4 (actually should be 0,1,2,3) because we have k words and index should be 0-k-1, hence %(k-1)!

def fullJustify(self, words, maxWidth):
    res, cur, num_of_letters = [], [], 0
    for w in words:
        if num_of_letters + len(w) + len(cur) > maxWidth:
            for i in range(maxWidth - num_of_letters):
                cur[i%(len(cur)-1 or 1)] += ' '
            res.append(''.join(cur))
            cur, num_of_letters = [], 0
        cur += [w]
        num_of_letters += len(w)
    return res + [' '.join(cur).ljust(maxWidth)]

The method ljust() returns the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(string).

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,163评论 0 10
  • 应和831班两位诗人昨日的诗作 —— 题记 就在昨天 漠河的第一场雪 因为一位南方诗人...
    江恨雨阅读 3,265评论 1 5
  • 今天去上班差一点迟到了,害得我下公交车就立即奔跑,还好,如果再差两分钟就迟到了,去的时候因为跑了一段路,所以累的我...
    万缕千丝阅读 1,631评论 0 1
  • 作者:盛明君 太阳给了地球一个抚摸 江河涌动了 春天给了秧苗一个抚摸 大地披绿了 微风给了树梢一个抚摸 百鸟鸣唱了...
    当代艺术阅读 3,203评论 0 3