例如: string = aaaacccc,那么我需要输出为4a4c。有没有办法做到这一点,而不使用任何高级方法,如库或函数?
另外,如果有人知道如何反其道而行之:将"4a4c:变成aaaacccc“,那就太好了。
发布于 2021-02-25 02:21:58
这将在一次迭代中完成工作
保留两个temp变量,一个用于当前字符,另一个用于字符计数,另一个用于结果。
只需迭代该字符串,如果它与前一个匹配,则不断增加计数。
如果不是,则使用字符的计数和值来更新结果,并更新字符和计数。
最后,将最后一个字符和计数添加到结果中。完成了!
input_str = "aaaacccc"
if input_str.isalpha():
current_str = input_str[0]
count = 0
final_string = ""
for i in input_str:
if i==current_str:
count+=1
else:
final_string+=str(count)+current_str
current_str = i
count = 1
final_string+=str(count)+current_str
print (final_string)发布于 2021-02-25 02:38:49
另一个解决方案,我甚至包括了一个拼凑的反向操作,就像你在帖子中提到的那样。它们的运行速度都是O(n),并且都很容易理解。编码基本上与Akanasha发布的相同,他只是在我编写decode()时发布他的答案快了一点。
def encode(x):
if not x.isalpha():
raise ValueError()
output = ""
current_l = x[0]
counter = 0
for pos in x:
if current_l != pos:
output += str(counter) + current_l
counter = 1
current_l = pos
else:
counter += 1
return output + str(counter) + current_l
def decode(x):
output = ""
i = 0
while i < len(x):
if x[i].isnumeric():
n = i + 1
while x[n].isnumeric():
n += 1
output += int(x[i:n])*x[n]
i = n
i += 1
return output
test = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasasggggggbbbbdd"
test1 = encode(test)
print(test1)
test2 = decode(test1)
print(test2)
print(test == test2)发布于 2021-02-25 02:09:28
是的,您不需要任何库:
list1 = list("aaaacccc")
letters = []
for i in list1:
if i not in letters:
letters.append(i)
string = ""
for i in letters:
string += str(list1.count(i))
string+=str(i)
print(string)基本上,它循环遍历列表,找到唯一的字母,然后打印字母本身的计数。反转是相同的功能,只需打印金额即可。
https://stackoverflow.com/questions/66356243
复制相似问题