<p>我正在努力解决这个问题。我见过其他涉及列表和使用递归的解决方案,但我对学习如何使用循环来解决这个问题感兴趣,我的问题是我无法打印最后一个字符,因为它等于一个空变量。你知道吗</p>
<pre><code>input:abbabd
expected output:aabd
</code></pre>
<hr/>
<p>代码:</p>
<pre><code>answer = input("enter a string: ")
new_answer = ""
p = ""
repeat = ""
len_answer = len(answer)
run = False
for c in answer:
if c != p and run == False:
new_answer += p
p = c
run = False
elif c == p:
p = c
run = True
elif run == True and c != p:
p = c
run = False
else:
new_answer += p
print(new_answer)
</code></pre>
<p>最简单的方法是:</p>
<pre><code>result = [[data[0], 1]]
for a in data[1:] :
if a == result[-1][0] :
result[-1][1] += 1
else :
result.append( [a,1] )
result = ''.join( [i[0] for i in result if i[1] == 1] )
</code></pre>