This problem was asked by Amazon.
Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count and character. For example, the string “AAAABBBCCDAA” would be encoded as “4A3B2C1D2A”.
Implement run-length encoding and decoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters. You can assume the string to be decoded is valid.
很简单,可以理解为双指针的思想。时间复杂度为O(N),N为输入字符串的长度。
def run_length_encoding(test_str):
ans = ""
i = j = 0
while i<len(test_str):
while j < len(test_str) and test_str[j] == test_str[i]:
j += 1
ans+=str(j-i)
ans+=test_str[i]
i = j
return ans
def run_length_decoding(test_str):
ans = ""
i = 0
while i<len(test_str):
j = 0
while i < len(test_str) and test_str[i] >= '0' and test_str[i] <= '9':
j *= 10
j += int(test_str[i])
i += 1
ch = test_str[i]
ans += ch * j
i += 1
return ans
test_str1 = "AAAABBBCCDAA"
test_str2 = "4A3B2C1D10A"
print(run_length_encoding(test_str1))
print(run_length_decoding(test_str2))