我试图解决一个编程问题的字符串转换为以下形式的字符串:
输入:aaaabbbcc
输出:a4b3c2
编码与Python
我的代码如下所示:
def encode(s):
output = []
i = 0
j = 1
while i < len(s) and j < len(s)-1 :
count = 1
output.append(s[j])
while s[i] == s[j] :
count += 1
j+=1
i+=1
output.append(count)
i += 1
j += 1
new_s = "".join(str(x) for x in output)
return new_s
但我得到以下例外:
回溯(最近呼叫最后):
File "encode.py", line 30, in
print encode(s)
File "encode.py", line 13, in encode
while s[i] == s[j] :
IndexError: string index out of range
我无法理解这里的错误。有人可以帮帮我吗?
你不检查对于j要出界的内环内... –
可能[字符串中出现字符的计数]的副本(https://stackoverflow.com/questions/1155617/count-occurrence-of-a-character-in-a-string) – ratskin
是的,谢谢了! –