擅长:python、mysql、java
<p>cnoder的一个可能的解决方案是简单地在字符串上迭代并计算字符出现的次数,不是很花哨,而是O(n)。在</p>
<pre><code>def encode(s):
last = s[0]
count = 0
for c in s:
if last != c:
yield '%s%i' % (last, count)
last = c
count = 0
count += 1
yield '%s%i' % (last, count)
</code></pre>
<p>对于解码器,您可以使用正则表达式来很好地拆分字符串,而不需要编写自己的解析器。在</p>
^{pr2}$
<p>根据你的测试输入</p>
^{3}$
<p>结果</p>
<pre><code>A3B4C1D10E2D4
AAABBBBCDDDDDDDDDDEEDDDD
</code></pre>
<p>还有一点,这里没有真正的理由使用yield,当然也可以先在en-/decode函数中构建字符串,然后返回。在</p>