如何检查字符串是否具有相同的字符?Python

2024-04-20 12:22:43 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

这是O(n)解决方案

from collections import Counter
Counter(str1) == Counter(str2)

但是使用sortedO(n * log n)解对于n的敏感值可能更快

以下是@Joowani解决方案的一个变体,它只使用一个字典,运行速度更快(至少在我的机器上):

def cmp4(str1, str2):
    if len(str1) != len(str2):
        return False
    d = collections.defaultdict(int)
    for c in str1:
        d[c] += 1
    for c in str2:
        d[c] -= 1
    return all(v == 0 for v in d.itervalues())

对两个字符串进行排序,然后进行比较:

sorted(str1) == sorted(str2)

如果字符串的长度可能不同,则可能需要首先确保该长度以节省时间:

len(str1) == len(str2) and sorted(str1) == sorted(str2)

相关问题 更多 >