📅  最后修改于: 2023-12-03 14:58:37.381000             🧑  作者: Mango
本题目是门|门CS 2012年中的一道编程题目,题目编号为36。该题目为一个字符串压缩和解压缩的问题。
给出一个字符串,编写一个程序实现以下两种功能:
def compress(str: str) -> str:
pass
def decompress(str: str) -> str:
pass
assert compress("aaaaaabbbbcccc") == "a6b4c4"
assert compress("abc") == "abc"
assert compress("aa") == "a2"
assert decompress("a6b4c4") == "aaaaaabbbbcccc"
assert decompress("abc") == "abc"
assert decompress("a2") == "aa"
该题目的难点在于字符串的压缩和解压缩。对于第一个问题,我们可以使用一个指针记录当前遍历的字符,一个计数器记录当前字符的数量,当遇到不同的字符时就将当前字符和数量添加到结果中,最后判断结果长度是否小于原字符串长度以决定是否返回原字符串。对于第二个问题,我们只需要遍历字符,如果当前字符是数字,就将后面的字符重复指定次数,否则就直接添加到结果中即可。
def compress(str: str) -> str:
res = ""
count = 1
for i in range(1, len(str)):
if str[i] == str[i - 1]:
count += 1
else:
res += str[i - 1] + str(count)
count = 1
res += str[-1] + str(count)
return res if len(res) < len(str) else str
def decompress(str: str) -> str:
res = ""
i = 0
while i < len(str):
if str[i].isnumeric():
num = int(str[i])
for j in range(num):
res += str[i + 1]
i += 2
else:
res += str[i]
i += 1
return res
代码片段的markdown如下:
```python
def compress(str: str) -> str:
res = ""
count = 1
for i in range(1, len(str)):
if str[i] == str[i - 1]:
count += 1
else:
res += str[i - 1] + str(count)
count = 1
res += str[-1] + str(count)
return res if len(res) < len(str) else str
def decompress(str: str) -> str:
res = ""
i = 0
while i < len(str):
if str[i].isnumeric():
num = int(str[i])
for j in range(num):
res += str[i + 1]
i += 2
else:
res += str[i]
i += 1
return res