# @param {String[]} words
# @param {Integer} max_width
# @return {String[]}
def full_justify(words, max_width)
temp_str = ""
j_words = []
words.each do |word|
if temp_str == ""
if (temp_str + word).length <= max_width
temp_str = temp_str + word
else
j_words.push(justify_spaces(temp_str, max_width))
temp_str = word
end
else
if (temp_str + " " + word).length <= max_width
temp_str = temp_str + " " + word
else
j_words.push(justify_spaces(temp_str, max_width))
temp_str = word
end
end
end
new_last = temp_str.split(" ").join(" ")
last_len = max_width - new_last.length
last_len.times do |i|
new_last = new_last + " "
end
j_words.push(new_last)
j_words
end
def justify_spaces(temp_str, max_width)
s_words = temp_str.split(" ")
s_len = s_words.length
space_count = max_width - temp_str.gsub(" ", "").length
space_count.times do |i|
index = 0
if s_len > 1
index = i % (s_len - 1)
end
s_words[index] = s_words[index].to_s + " "
end
s_words.join("")
end
LeetCode 68 Text Justification
最新推荐文章于 2021-07-12 22:49:24 发布
本文介绍了一种文本布局算法的实现方法,该算法可以将给定的一组单词在规定的最大宽度内进行合理排列,并确保每行文字之间的间距尽可能均匀。特别地,文章详细解释了如何通过Ruby代码来实现这一功能。

331

被折叠的 条评论
为什么被折叠?



