在一个字符串在Python中删除重复 [英] Removing duplicates in a string in Python

查看:187
本文介绍了在一个字符串在Python中删除重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是有效的算法来消除所有重复的字符串?

What is an efficient algorithm to removing all duplicates in a string?

例如: aaaabbbccdbdbcd

所需的结果: ABCD

推荐答案

您使用哈希表通过数组来存储当前发现的密钥(访问O(1)),然后循环。如果一个角色是在哈希表,丢弃它。如果它不将其添加到散列表和一个结果字符串

You use a hashtable to store currently discovered keys (access O(1)) and then loop through the array. If a character is in the hashtable, discard it. If it isn't add it to the hashtable and a result string.

总体:O(n)时间(和空间)

Overall: O(n) time (and space).

天真的解决方法是搜索字符结果字符串为您处理每一个。这为O(n 2 )。

The naive solution is to search for the character is the result string as you process each one. That O(n2).

这篇关于在一个字符串在Python中删除重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆