Python - 字符串是否包含另一个字符串中的所有字符? [重复]

问题描述 投票:1回答:2

这个问题在这里已有答案:

我需要检查字符串是否包含一组字符,并且它们需要显示正确的次数。

string1 = "somestring"
string2 = "thestrings"
characters = "egimnorsst" # Note that there are two 's' characters here
does_string_contain(string1, characters) # True
does_string_contain(string2, characters) # False
python string
2个回答
5
投票

只需对它们进行排序和比较

>>> sorted("egimnorsst") == sorted("somestring")
True

2
投票

一种方式是collections.Counter

对于sorted,该方法具有O(n)对O(n log n)的复杂性。

from collections import Counter

string1 = "somestring"
string2 = "egimnorsst"

Counter(string1) == Counter(string2)  # True

对于大字符串,此方法比排序更有效:

from collections import Counter
import random, string

def random_string(length):
    return ''.join(random.choice(string.ascii_letters) for m in range(length))

n = 50000
string1 = random_string(n)
string2 = ''.join(random.sample(string1, n))

%timeit Counter(string1) == Counter(string2)  # 11.3 ms
%timeit sorted(string1) == sorted(string2)    # 41.6 ms
© www.soinside.com 2019 - 2024. All rights reserved.