2021-01-02 Python百日打卡学习自【夸可编程】

题目:
给定2个字符串str1,str2,判断str1是否是str2的一个排列

例子:
‘Hello’,'Hlleo' -> True
'Hello', 'hlleo' -> False
'Cat', 'Catt' -> False
'world', 'dlwor' -> True

假设"
字符串都是ASCII字符
大小写敏感

def is_permutation(str1, str2):
    if str1 is None or str2 is None:
        return False
    return set(sorted(str1)) == set(sorted(str2))

# 使用collections中的计数器
from collections import Counter
def another(str1, str2):
    if str1 is None or str2 is None:
        return False
    if len(str1) != len(str2):
        return False
    c1 = Counter(str1)
    print(c1, type(c1))
    c2 = Counter(str2)
    print(c2)
    #tets
    # c3 = Counter(cats=3, dogs=8)
    # print(list(c3.elements()))  -------['cats', 'cats', 'cats', 'dogs', 'dogs', 'dogs', 'dogs', 'dogs', 'dogs', 'dogs', 'dogs']
    # print(c3)   ---- Counter({'dogs': 8, 'cats': 3})
    return c1 == c2

str1 = 'Hello'
str2 = 'elloH'
print(is_permutation(str1, str2))

print(another(str1, str2))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容