# @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
最新推荐文章于 2020-09-08 19:13:08 发布