注意一、不要将字符串分割,空格也算有效输入字符,也要进行计数
注意二、在压缩时,要使循环多进行一轮(方便将结果加入到结果中,这样程序更简单),在字符串末尾多加一个字符即可
注意三、解码时,数字不一定是个位数(有可能大于9),需要把数字字符串拼接起来
n = input()
char = input()
result = ""
if n == "C":
same = ""
count = 0
char += "0" # 在字符串后面多加一个字符0,使循环多进行一轮
for ch in char:
if same != ch:
if same != "":
if count == 1:
result += same
else:
result += str(count) + same
same = ch
count = 1
else:
count += 1
else:
count = ""
for ch in char:
if 48 <= ord(ch) <= 57:
count += ch # 数字有可能有多位,用字符串拼接起来
else:
if count == "":
result += ch
else:
result += ch * int(count)
count = ""
print(result)
在压缩时,使第一个字符成为判断标准,计数设置为1,可以减少一个if语句,并少循环一轮
n = input()
char = input()
result = ""
if n == "C":
same = char[0]
count = 1
char += "0" # 在字符串后面多加一个字符0,使循环多进行一轮
for ch in char[1:]:
if same != ch:
if count == 1:
result += same
else:
result += str(count) + same
same = ch
count = 1
else:
count += 1
else:
count = ""
for ch in char:
if 48 <= ord(ch) <= 57:
count += ch # 数字有可能有多位,用字符串拼接起来
else:
if count == "":
result += ch
else:
result += ch * int(count)
count = ""
print(result)
|