我想将字符附加到字符串,但要确保最终列表中的所有字母都是唯一。
I want to append characters to a string, but want to make sure all the letters in the final list are unique.
示例:aaabcabccd→abcd
当然,我心里有两个解决方案。一个是使用一个列表来映射字符与其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.
更多推荐
字符串中所有唯一字符的列表?
发布评论