在一个字符串在Python中删除重复在一、字符串、Python

2023-09-11 04:17:11 作者:恰似显出

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

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).