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))
本文介绍了run-lengthencoding(字符重复计数编码)的概念,以及如何使用Python实现该算法的编码和解码函数。编码过程利用双指针技巧,时间复杂度为O(N),N为输入字符串长度。给出两个示例测试用例进行验证。
350

被折叠的 条评论
为什么被折叠?



