Problem #29 [Easy]

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值