首页 > 试题广场 >

字符串压缩

[编程题]字符串压缩
  • 热度指数:8690 时间限制:C/C++ 5秒,其他语言10秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
对字符串进行 RLE 压缩,将相邻的相同字符,用计数值和字符值来代替。例如:aaabccccccddeee,则可用 3a1b6c2d3e 来代替

数据范围:字符串长度满足

输入描述:
输入为a-z,A-Z的字符串,且字符串不为空,如aaabccccccddeee


输出描述:
压缩后的字符串,如3a1b6c2d3e
示例1

输入

aaabccccccdd

输出

3a1b6c2d
while True:
    try:
        s = '.'
        s = s + input()
        s = s + '.'
        ss = ''
        c = 1
        for i in range(1, len(s)-1):
            if s[i] == s[i-1] and s[i] == s[i+1]:
                c = c + 1
            if s[i] == s[i-1] and s[i] != s[i+1]:
                c = c + 1
                ss = ss + str(c) + s[i]
                c = 1
            if s[i] != s[i-1] and s[i] != s[i+1]:
                c = 1
                ss = ss + str(c) + s[i]
        print(ss)
    except:
        break

发表于 2020-05-04 10:13:20 回复(0)
p = q = r = ''
for i in input():
    if i == p:
        r += 1
    else:
        q,p,r = q + str(r) + p,i,1
print(q + str(r) + p)

发表于 2020-03-14 11:29:44 回复(0)
s = input()
i = 0
res = ''
while i < len(s):
    cnt = 0
    while s[i+cnt] == s[i]:
        cnt += 1
        if i+cnt >= len(s):
            break
    res += str(cnt)
    res += s[i]
    i += cnt
print(res)

发表于 2019-09-10 09:58:58 回复(0)
s = list(input())
word = [] for elem in s: if elem not in word:
        word.append(elem)
dic = dict()
result = '' for elem in s: if elem in dic.keys():
        dic[elem]+=1  else:
        dic[elem] = 1 for param in word:
    result += str(dic[param])
    result+=param print(result)
发表于 2019-08-11 22:42:21 回复(0)
"""
字符串压缩
"""
import sys

if __name__ == "__main__":
    # sys.stdin = open("input.txt", "r")
    s = input().strip()
    count = 1
    ans = ""
    for i in range(1, len(s)):
        if s[i] == s[i - 1]:
            count += 1
        else:
            ans += str(count) + s[i - 1]
            count = 1
    ans += str(count) + s[-1]
    print(ans)

发表于 2019-07-10 11:16:03 回复(0)
主要是参考了前面几位老哥的解法,用Python重写了一下
使用列表存储 次数和字母,然后转换成string类型输出就可以了
使用字典的情况下,不能保证输出的顺序
texts = raw_input()
def get_string(texts):
    count = 0
    list_freq = []
    for index in range(len(texts)):
        count += 1  
        if index == len(texts) - 1 or texts[index] != texts[index+1]:
            list_freq.append(count)
            list_freq.append(texts[index])
            count = 0
    print "".join("%s" % freq for freq in list_freq)

if __name__ == "__main__":
    get_string(texts)

编辑于 2019-06-30 14:44:20 回复(0)