如果使用递归方法实现此目的,则可以轻松跟踪最后出现的字符及其当前计数,以及保存到目前为止结果的累加器。如果当前字符等于最后一个字符,则只需增加计数即可。如果两者不同,则将最后一个字符及其计数添加到累加器中,然后继续处理下一个字符,直到字符串为空。最后,对最终值进行编码并返回结果。
defmodule RunLengthEncoding do
# public interface, take first char and remember it as the current value
def encode(<<char::utf8, rest::binary>>) do
do_encode(rest, char, 1, "")
end
# current == last, increase the count and proceed
defp do_encode(<<char::utf8, rest::binary>>, char, count, acc) do
do_encode(rest, char, count + 1, acc)
end
# current != last, reset count, encode previous values and proceed
defp do_encode(<<char::utf8, rest::binary>>, last, count, acc) do
do_encode(rest, char, 1, acc <> to_string(count) <> <<last::utf8>>)
end
# input empty, encode final values and return
defp do_encode("", last, count, acc) do
acc <> to_string(count) <> <<last::utf8>>
end
end