下班之后,实在不想太动脑筋想问题,直接正则表达式分割字符串,借助哈希解决此题
3167. 字符串的更好压缩
# @param {String} compressed
# @return {String}
def better_compression(compressed)
compress1 = compressed.split(/[0-9]/)
compress2 = compressed.split(/[a-z]/)
compress1.select! {|it| it != ""}
compress2.select! {|it| it != ""}
h = {}
compress1.each_with_index do |c,i|
unless h.has_key?(c)
h[c] = compress2[i].to_i
else
h[c] += compress2[i].to_i
end
end
h.keys.sort.map {|it| it + h[it].to_s}.join
end