我試圖解決一個編程問題的字符串轉換爲以下形式的字符串:
輸入: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
是的,謝謝了! –