算法-变位词

# 逐一比对法
def func1(s1: str, s2: str):
if len(s1) != len(s2):
return False
for i in range(len(s1)):
if s1[i] in s2:
s2 = s2.replace(s1[i], '')
if s2 == '':
return True
else:
return False


# 排序比较法
def func2(s1: str, s2: str):
if len(s1) != len(s2):
return False
ls1 = sorted(list(s1))
ls2 = sorted(list(s2))
if ls1 == ls2:
return True
return False


# 暴力法


# 计数法
def func3(s1: str, s2: str):
if len(s1) != len(s2):
return False
c1 = [0] * 26
c2 = [0] * 26
for i in s1:
c1[ord(i) - ord('a')] += 1
for i in s2:
c2[ord(i) - ord('a')] += 1
if c1 == c2:
return True
return False


if __name__ == '__main__':
s1 = 'eeeeec'
s2 = 'ceeeee'
print(func1(s1, s2))
print(func2(s1, s2))
print(func3(s1, s2))
posted @ 2022-04-28 17:14  狒狒桑  阅读(27)  评论(0编辑  收藏  举报