题目:
给定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))