对字符串进行 RLE 压缩,将相邻的相同字符,用计数值和字符值来代替。例如:aaabccccccddeee,则可用 3a1b6c2d3e 来代替。
数据范围:字符串长度满足 
输入为a-z,A-Z的字符串,且字符串不为空,如aaabccccccddeee
压缩后的字符串,如3a1b6c2d3e
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
""" 字符串压缩 """ 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)
主要是参考了前面几位老哥的解法,用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)