我有一个字符串,需要去除相邻重复的单词。
mystring = "my friend's new new new new and old old cats are running running in the street"
我的输出应该如下所示。
myoutput = "my friend's new and old cats are running in the street"
我正在使用以下 Python 代码来完成此操作。
mylist = []
for i, w in enumerate(mystring.split()):
for n, l in enumerate(mystring.split()):
if l != w and i == n-1:
mylist.append(w)
mylist.append(mystring.split()[-1])
myoutput = " ".join(mylist)
然而,我的代码的时间复杂度是O(n²),由于数据集非常庞大,效率很低。我想知道是否有更高效的Python解决方法。如果需要更多细节,我很乐意提供。