1 案例1 leetcode-----242

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。

示例 1:

输入: s = "anagram", t = "nagaram"
输出: true

python版本

方法1:直接排序

方法二:API map计数

方法三:数组模拟hash

 1 '''
 2 方法1 按照字母序排序 如果一样则是 时间复杂度是nlogN 快排
 3 
 4 方法2 数字符串每个字符串字符的个数,也就是使用map来计算{letter:count}
 5 a---->3
 6 n---->1
 7 r---->1
 8 时间复杂度O(N) *1 为O(N)
 9 '''
10 
11 class Solution(object):
12     def isAnagram(self, s, t):
13         """
14         :type s: str
15         :type t: str
16         :rtype: bool
17         """
18         #方法一
19         #return sorted(s)==sorted(t)
20         
21         #方法二
22         '''
23         dic1,dic2={},{}
24         for item in s:
25             dic1[item]=dic1.get(item,0)+1
26         for item in t:
27             dic2[item]=dic2.get(item,0)+1
28         return dic1==dic2
29         '''
30         #方法三
31         dic1,dic2=[0]*26,[0]*26
32         for item in s:
33             dic1[ord(item)-ord('a')]+=1
34         for item in t:
35             dic2[ord(item)-ord('a')]+=1
36         return dic1==dic2
37         
View Code

相关文章:

  • 2022-12-23
  • 2021-11-04
  • 2022-12-23
  • 2021-07-20
  • 2022-12-23
  • 2022-12-23
  • 2021-04-11
猜你喜欢
  • 2021-11-28
  • 2021-07-27
  • 2022-12-23
  • 2021-05-29
  • 2021-07-15
  • 2022-12-23
  • 2021-09-04
相关资源
相似解决方案