File tree 1 file changed +41
-0
lines changed
1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+
2
+ class Solution :
3
+ """
4
+ 242. 有效的字母异位词
5
+ https://leetcode-cn.com/problems/valid-anagram/description/
6
+ 给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
7
+ """
8
+ # map 方法
9
+ def isAnagram (self , s : str , t : str ) -> bool :
10
+ if len (s ) != len (t ):
11
+ return False
12
+
13
+ m = {}
14
+ for i in range (len (s )):
15
+ if s [i ] not in m :
16
+ m [s [i ]] = 1
17
+ else :
18
+ m [s [i ]] += 1
19
+
20
+ for j in range (len (t )):
21
+ if t [j ] not in m :
22
+ return False
23
+ else :
24
+ m [t [j ]] -= 1
25
+
26
+ for v in m .values ():
27
+ if v != 0 :
28
+ return False
29
+ return True
30
+
31
+
32
+ # 排序
33
+ def isAnagramBySort (self , s : str , t : str ) -> bool :
34
+ s_sorted = '' .join (sorted (s ))
35
+ t_sorted = '' .join (sorted (t ))
36
+ return s_sorted == t_sorted
37
+
38
+
39
+
40
+ so = Solution ()
41
+ print (so .isAnagram ('aa' , 'bb' ))
You can’t perform that action at this time.
0 commit comments