leetcode242之有效的字母异位词

题目描述:

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

示例 1:

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

示例 2:

输入: s = "rat", t = "car"
输出: false

代码实现:
 1 from collections import Counter
 2 
 3 def isyiwei(s, t):
 4     '''
 5     判断s是否为t的字母异位词
 6     :param s:
 7     :param t:
 8     :return:
 9     '''
10     s = list(s)
11     t = list(t)
12     if len(s) == len(t):
13         for i in s:
14             if i in t:
15                 t.remove(i)
16             else:
17                 return False
18     else:
19         return False
20 
21     return True
22 
23 
24 print("---------测试isyiwei()------------")
25 s = "rat"
26 t = "car"
27 print(isyiwei(s, t))
28 
29 def isyiwei1(s, t):
30     '''
31     哈希表判断
32     :param s:
33     :param t:
34     :return:
35     '''
36     s_dict = dict(Counter(s))
37     t_dict = dict(Counter(t))
38     print(s_dict)
39     print(t_dict)
40 
41     if len(s_dict) == len(t_dict):
42         for i in s_dict:
43             if i in t_dict and s_dict[i] == t_dict[i]:
44                 continue
45             else:
46                 return False
47     else:
48         return False
49 
50     return True
51 
52 
53 print(isyiwei1(s, t))

总结:上述采取两种方法来判断,第一种为列表形式,首先判断两个列表长度是否相等,若相等则继续,遍历s中一个元素,若在t中也找到,则在t中去掉该元素,继续循环遍历下一元素,直至结束,返回True;在判断过程中,若出现s中元素不存在t中,返回False。若两列表长度不等,直接返回False。

方法2采用哈希表形式,调用collections.Counter()对象进行元素计数并转为字典,和方法1很相似,判断两字典长度是否相等,若相等继续判断字典s_dict中元素是否全部存在于t_dict中,直至判断结束,返回True,否则返回False

原文地址:https://www.cnblogs.com/rounie/p/13511700.html