问题
There is a linear time algorithm (or quadratic time algorithm by Knuth & Plass) for breaking text evenly into lines of maximum width. It uses SMAWK and "evenly" means:
http://en.wikipedia.org/wiki/Word_wrap#Minimum_raggedness
Is there an algorithm or a concave cost function for algorithm above which would take into account the number of lines I would like the text break into, instead of the maximum line width?
In other words, I'm looking for a line breaking (or paragraph formation, or word wrapping) algorithm where the input is the desired number of lines, not the desired line width.
Just to describe a practically unusable approach: There are N words and N-1 spaces in-between each word pair, M is the desired number of lines (M <= N). After each space there might be at most one (possibly zero) line-break. Now, the algorithm would try to place the breaks in each possible combination, calculating the "raggedness" and return the best one. How to do it much faster?
回答1:
You could simply reduce the problem of achieving a given number of lines to the problem of breaking lines after a maximum length by calculating the maximum length as the total length of the string divided by the number of lines you want. As the actual length of a line is going to be less than the maximum length in many cases, you would probably need to subtract 1 from the number of lines you want.
来源:https://stackoverflow.com/questions/9515867/break-text-evenly-into-certain-number-of-lines