返回
文本左右对齐(#68 题解)——原题、解析、解答全都有
闲谈
2023-12-31 07:10:28
引言
嗨,大家好!我是顾毅,一位 Netflix 增长黑客、《iOS 面试之道》的作者,也是一位 ACE 职业健身教练。今天,我将与大家分享 LeetCode #68 题「文本左右对齐」的 Swift 算法题解。这道题考察了字符串处理的能力,对初学者来说是一个很好的挑战。
题目原题
给定一个字符串数组 words
,以及一个整数 maxWidth
。将 words
中的单词重新排列,使得每一行最多有 maxWidth
个字符,并且每一行两端的空格数相同。如果不能均匀分配空格,则左侧多出的空格数较多。每个单词只能被使用一次。
算法解析
这道题的解题思路是使用贪心算法。具体步骤如下:
- 将字符串数组
words
从前往后遍历,并将单词依次添加到当前行中。 - 如果当前行的长度加上下一个单词的长度大于
maxWidth
,则将当前行中的单词左右对齐并输出,然后开始新的一行。 - 如果当前行的长度加上下一个单词的长度小于或等于
maxWidth
,则将下一个单词添加到当前行中。 - 重复步骤 2 和 3,直到将所有单词添加到输出中。
代码解答
func fullJustify(_ words: [String], _ maxWidth: Int) -> [String] {
var result: [String] = []
var currentLine: [String] = []
var currentLineWidth = 0
for word in words {
let wordLength = word.count
if currentLineWidth + wordLength + currentLine.count > maxWidth {
result.append(justify(currentLine, maxWidth - currentLineWidth))
currentLine.removeAll()
currentLineWidth = 0
}
currentLine.append(word)
currentLineWidth += wordLength + 1
}
if currentLine.count > 0 {
result.append(justify(currentLine, maxWidth - currentLineWidth + currentLine.count - 1))
}
return result
}
func justify(_ words: [String], _ width: Int) -> String {
var result = ""
let wordCount = words.count
var spaceCount = wordCount - 1
var spaceWidth = 0
if spaceCount > 0 {
spaceWidth = width / spaceCount
}
var extraSpaceCount = width - spaceCount * spaceWidth
for (i, word) in words.enumerated() {
result += word
if i < wordCount - 1 {
result += String(repeating: " ", count: spaceWidth)
if i < extraSpaceCount {
result += " "
}
}
}
return result
}
结语
好了,以上就是 LeetCode #68 题「文本左右对齐」的 Swift 算法题解。希望对大家有所帮助。如果您还有其他问题,欢迎随时给我留言。
参考
作者简介
顾毅,Netflix 增长黑客、《iOS 面试之道》作者,ACE 职业健身教练。长期致力于 iOS 开发和算法研究,在多家互联网公司担任过技术负责人。目前在 Netflix 担任增长黑客,负责用户增长和留存工作。