解题思路
- 先比较俩字符串的长度是否一致
- 将字符串转为列表
- 将两个字符串用sort()排序
- 依次对比每个字母是否相等
本算法时间主导的步骤为排序sort()
所以本算法的运行时间数量级等于排序过程的时间数量级:O(nlogn)
参考:【北京大学】数据结构与算法Python版(完整版)2.3.1:https://www.bilibili.com/video/BV1VC4y1x7uv?p=10
代码
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) == len(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
matches = True
else:
matches = False
return matches
else:
return False

961

被折叠的 条评论
为什么被折叠?



