返回
我的 LeetCode 征途:征服「文本左右对齐」
前端
2023-12-22 05:32:15
**前言**
哈喽,各位算法工程师们!今天,我们开启 LeetCode 征途的下一站:**「文本左右对齐」** 。这个看似简单的挑战,却暗藏着算法的精髓。准备好迎接挑战了吗?
**算法本质**
「文本左右对齐」本质上是一个字符串处理问题。我们的目标是将给定的文本行对齐,满足以下规则:
* 如果是文本的最后一行,则左对齐,不足部分用空格补齐。
* 如果文本行中只有一个单词,则左对齐,不足部分用空格补齐。
* 如果文本行中有多个单词,则单词间用空格隔开,不足部分左右对齐。
**代码实现**
掌握了算法本质,接下来就是代码实现的时刻了。我们使用 Python 作为示例语言,一步步拆解算法逻辑:
```python
def justify(words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
# 初始化结果列表和当前行
result = []
current_line = []
# 遍历单词
for word in words:
# 如果当前行长度加上单词长度和一个空格后超过最大宽度
if len(current_line) + len(word) + 1 > maxWidth:
# 处理当前行
result.append(format_line(current_line, maxWidth))
# 清空当前行并添加单词
current_line = [word]
else:
# 添加单词和空格
current_line.append(word)
current_line.append(' ')
# 处理最后一行
result.append(format_line(current_line, maxWidth))
return result
def format_line(words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: str
"""
# 如果是最后一行或只有一个单词,则左对齐
if len(words) == 1 or maxWidth == len(''.join(words)):
return ' '.join(words).ljust(maxWidth)
# 否则,左右对齐
spaces = maxWidth - len(''.join(words))
avg_spaces = spaces // (len(words) - 1)
extra_spaces = spaces % (len(words) - 1)
# 构建格式化行
formatted_line = ''
for i in range(len(words) - 1):
formatted_line += words[i]
formatted_line += ' ' * (avg_spaces + (i < extra_spaces))
# 添加最后一个单词
formatted_line += words[-1]
return formatted_line
总结
「文本左右对齐」算法看似简单,却蕴含着算法思维的魅力。通过将问题拆解为不同情况并逐一处理,我们可以构建出高效的解决方案。希望这次 LeetCode 征途能带给你新的启发和收获!