字符串中所有唯一字符的列表?

编程入门 行业动态 更新时间:2024-10-17 07:34:15
本文介绍了字符串中所有唯一字符的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

字符串中所有唯一字符的列表?

本文发布于:2023-11-29 12:33:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646406.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   字符   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!