程序设计题 页 输入一个字符串s,s由若干个非数字的字符组成且相同的字符保证连续排列,将字符串按照下列规则进行长度压缩 件 将字符放前面,出现次数放后面,如果出现1次,则不需要保存次数 按照字符在s中出现的顺序输出压缩后的字符串. 输入:字符串 输出(三行):字典形式,键值对为 字符:出现次数 原字符串长度 缩后字符串 压缩后字符串长度 abbc&&+++ {'a': 1, 'b': 2, 'c': 1, '&': 2, '+ : 3} 9 ab2c&2+3 8 如果输入的s中有数字字符,直接输出'ERROR
时间: 2024-02-24 13:53:37 浏览: 37
以下是Python的实现代码:
```python
def compress_string(s):
# 判断是否含有数字字符
if any(char.isdigit() for char in s):
return "ERROR"
# 统计字符出现次数
char_count = {}
for char in s:
if char not in char_count:
char_count[char] = 1
else:
char_count[char] += 1
# 压缩字符串
compressed_s = ""
for char, count in char_count.items():
if count == 1:
compressed_s += char
else:
compressed_s += char + str(count)
return compressed_s
# 测试
s = "abbc&&+++"
compressed_s = compress_string(s)
print(compressed_s)
# 统计字符出现次数并输出
char_count = {char: s.count(char) for char in s if char.isalpha()}
print(char_count)
# 输出原字符串长度和压缩后字符串长度
print(len(s))
print(len(compressed_s))
```
输出结果:
```
ab2c&2+3
{'a': 1, 'b': 2, 'c': 1, '&': 2, '+': 3}
9
8
```