Google VO 面试真题解析:字符串换行与文本折行(Text Wrapping, Max Width)

22次阅读
没有评论

Input is a string and a maximum width length. If a word is too long to fit into one line, we change line and move it to the other line.

Implement a Python algorithm for this, with algorithm and code comments on each line to explain.

这道题考查的是字符串处理与文本折行。给定一段文本和最大行宽,需要按单词顺序进行排版:当前行放不下时就换到下一行,必要时把超长单词放到新行中。实现时通常会用线性扫描维护当前行长度,逐个处理单词并决定是追加空格还是换行。关键是正确处理边界情况,例如单词本身超过行宽、空格拼接以及最后一行收尾。

正文完
 0