字符串中所有唯一字符的列表? [英] List of all unique characters in a string?

查看:167
本文介绍了字符串中所有唯一字符的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将字符附加到字符串,但要确保最终列表中的所有字母都是唯一

I want to append characters to a string, but want to make sure all the letters in the final list are unique.

示例:aaabcabccdabcd

当然,我心里有两个解决方案。一个是使用一个列表来映射字符与其ASCII码。所以每当遇到一封信时,它都会将索引设置为 True 。之后,我将扫描列表并附加所有设置的列表。它将具有 O(n)的时间复杂度。

Now of course I have two solutions in my mind. One is using a list that will map the characters with their ASCII codes. So whenever I encounter a letter it will set the index to True. Afterwards I will scan the list and append all the ones that were set. It will have a time complexity of O(n).

另一个解决方案是使用 dict 并按照相同的过程。在映射每个字符后,我将对字典中的每个键进行操作。这将具有线性运行时间。

Another solution would be using a dict and following the same procedure. After mapping every char, I will do the operation for each key in the dictionary. This will have a linear running time as well.

由于我是一个Python新手,我想知道哪个更有效率。哪一个可以更有效地实施?

Since I am a Python newbie, I was wondering which would be more space efficient. Which one could be implemented more efficiently?

PS :订单是 重要

PS: Order is not important while creating the list.

推荐答案

最简单的解决方案可能是:

The simplest solution is probably:

In [10]: ''.join(set('aaabcabccd'))
Out[10]: 'acbd'

请注意,这并不能保证字母出现在输出中的顺序,即使示例可能会另外出现。

Note that this doesn't guarantee the order in which the letters appear in the output, even though the example might suggest otherwise.

将输出称为列表。如果列表是您真正想要的,请将''加入列表

You refer to the output as a "list". If a list is what you really want, replace ''.join with list:

In [1]: list(set('aaabcabccd'))
Out[1]: ['a', 'c', 'b', 'd']

就性能而言,在这个阶段担心它听起来像过早优化。

As far as performance goes, worrying about it at this stage sounds like premature optimization.

这篇关于字符串中所有唯一字符的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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