【问题标题】:Python - Does string contain all characters in another string? [duplicate]Python - 字符串是否包含另一个字符串中的所有字符? [复制]
【发布时间】:2018-08-10 04:18:17
【问题描述】:

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

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


    【解决方案1】:

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

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

    【讨论】:

    • @JuanTheron +1 cmets 不赞成...这就是点赞按钮的用途 :)
    • 大声笑,好吧 whateva.... 对不起
    【解决方案2】:

    一种方法是collections.Counter

    此方法的复杂度为 O(n),而 sorted 的复杂度为 O(n log n)。

    from collections import Counter
    
    string1 = "somestring"
    string2 = "egimnorsst"
    
    Counter(string1) == Counter(string2)  # True
    

    对于大字符串,这种方法比 sorted 更高效:

    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
    

    【讨论】:

    • 这会比对每个字符串排序更快吗?
    • 对于更大的字符串,是的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2013-03-13
    • 2011-08-31
    • 2019-06-07
    • 1970-01-01
    相关资源
    最近更新 更多