Python数据结构 --- 字母异位词

 给定两个字符串 s1 和 s2 ,编写一个函数来判断 s2 是否是 s1的字母异位词。
#
# 注意:若s1 和 s2中每个字符出现的次数都相同,则称s1 和 s2互为字母异位词。
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/valid-anagram

# 解决方案一:对s1中的每个字符 去与S2中的每个字符作比较 ,当找到相同字符 做标记,未找到,失败.时间复杂度O(n^2)
def anagramSolution(s1, s2):
alist = list(s2) #将字符串s2复制到列表
pos1 = 0
stillOK = True
while pos1 < len(s1) and stillOK: # 循环s1中每个字符
pos2 = 0
found = False
while pos2 < len(alist) and not found:
if s1[pos1] == alist[pos2]: #在s2逐个对比
found = True
else:
pos2 = pos2 + 1
if found:
alist[pos2] = None #找到 打勾
else:
stillOK = False #未找到 失败
pos1 = pos1 + 1
return stillOK


print(anagramSolution('abcd','dbca'))

# 第二种解法  先将字符串按照字母顺序排列好序  再逐个比对字符是否相同, 若相同则是异位词,有任何不同则不是

def anagramSolution_2(s,t):
alist1 = list(s) #转为列表
alist2 = list(t)

alist1.sort() #分别排序
alist2.sort()
pos = 0
matches = True
while pos < len(s) and matches:
if alist1[pos] == alist2[pos]: #逐个对比
pos = pos + 1
else:
matches = False
return matches

print(anagramSolution_2('abcde','bdcae'))


# 初看上去,算法只有一个循环 最多执行N次 时间复杂度为O(n)
# 但循环前面的 sort并不是无代价的 O(NlogN)

# 第三种解法  对比两个词中每个字母出现的次数   ,如果26个字母出现的次数相同,这两个字符串一定是字母异位词
# 具体做法 为每个词设置一个26位的计数器 先检查每个词 在计数器中设定好每个字母出现的次数,计数完成后
# 进入比较阶段,看两个字符串的计数器是否相同,如果相同则输出是字母异位词的结论
def anagramSolution(s,t):
c1 = [0] * 26
c2 = [0] * 26
for i in range(len(s)): #分别都计数
pos = ord(s[i]) - ord('a')
c1[pos] = c1[pos] + 1
for i in range(len(t)):
pos = ord(t[i]) - ord('a')
c2[pos] = c2[pos] + 1
j = 0
stillOK = True
while j < 26 and stillOK: #计数器比较
if c1[j] == c2[j]:
j = j +1
else:
stillOK = False
return stillOK

print(anagramSolution('apple','pleap'))

ps.这是在b站上看到的搬运陈斌老师的课,感觉老师讲课真的很好





posted @ 2022-03-22 21:57  ChouchouYa  阅读(264)  评论(0)    收藏  举报