我想开发一种递归自动换行算法,该算法采用指定的字符串和换行长度(一行上的最大字符数)来返回输入长度的换行输出。我不想让它拆散单词。例如,这是您需要输入的第一段
,长度为 20 返回为:
This is the first
paragraph that you
need to input
我已经实现了动态编程(自下而上)的解决方案,但我想知道是否可以编写一个算法来仅使用递归(自上而下)来实现此目的?如果可以的话我也想记住它。请不要给我任何可运行的代码...我只是想知道想法/伪代码。
最佳答案
像下面的伪代码这样的东西应该可以工作。 (我确信如果我犯了错误,我们会收到评论!)
function Wrap(the_text,line_len)
if length(the_text) > line_len then
text_bit = the first few words of the_text, keeping their length shorter than line_len
remove text_bit from the beginning of the_text
return text_bit + linefeed + Wrap(the_text, line_len)
else
return the_text
end if
end function
关于algorithm - 是否可以开发一种递归自动换行算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23962882/