Word wrap to X lines instead of maximum width (Least raggedness)

后端 未结 8 1758

Does anyone know a good algorithm to word wrap an input string to a specified number of lines rather than a set width. Basically to achieve the minimum width for X lines.

8条回答
  •  既然无缘
    2020-12-09 13:45

    I'll assume you're trying to minimize the maximum width of a string with n breaks. This can be done in O(words(str)*n) time and space using dynamic programming or recursion with memoziation.

    The recurrence would look like this where the word has been split in to words

    def wordwrap(remaining_words, n):
        if n > 0 and len(remaining_words)==0:
            return INFINITY  #we havent chopped enough lines
    
        if n == 0:
            return len(remaining_words.join(' ')) # rest of the string
    
        best = INFINITY
        for i in range remaining_words:
            # split here 
            best = min( max(wordwrap( remaining_words[i+1:], n-1),remaining_words[:i].join(' ')), best  )  
    
        return best
    

提交回复
热议问题