力扣242有效字母异分词
1.看到题目,“异分词”就是查看s中有的字母和t中有的字母是否相同,本能暴力想法就是把s和t中的字母挨个对比一遍,如果完全重合(互相拥有彼此包含的字母),那么就返回true。
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
len1=len(s)
len2=len(t)
if len1!=len2:
return False#长度如果不等肯定不异分词
temp=[0]*len1
for i in range(len1):
for j in range(len2):
if temp[j]==0 and s[i]==t[j]:
temp[j]=1#标记出现过的元素
break
j+=1
i+=1
for i in range(len(temp)):
if temp[i]==0:
return False#t有的元素s中没有
return True
很遗憾,leetcode未给通过,因为超时,O(2)确实暴力。
2.看了代码随想录的题解,这道题被放在了《哈希》知识点部分,我反复斟酌应该是一种怎样的映射关系。其实对比两个数组、字符串、字符数组等容器的时候,如果两个容器元素所在的定义域是相同的时候,那么其实可以考虑哈希。比如说,对比数组array1和数组array2是否满足异分词,array1和array2中的元素都来自[0,100],那么可以用array1和array2中[0,100]出现的次数作为哈希映射。哈希表为长度100,初值为0的数组temparray,array1中出现77则temparray[77]+=1,本题字符串也是相同的道理,代码如下:
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
len1=len(s)
len2=len(t)
if len1!=len2:
return False
temp=[0]*26
for i in range(len1):
temp[ord(s[i])-ord('a')]+=1
for i in range(len2):
temp[ord(t[i])-ord('a')]-=1
for i in range(26):#最终s有的t中没有,或者t中有的s中没有,返回False
if temp[i]!=0:
return False
return True
3.python积累:
(1)求长度为n的zero数组:[0]*n
(2)将字符转换为ASCII码:ord(‘char’)
力扣349两个数组的交集
1.首先看到求交集的题目应该朝着python内置函数的方向思考,最简单的就是运用python求交集符号&。
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))
2.set1 & set2 求set1和set2的交集(就是共同拥有的元素)
set1 | set2求set1和set2的并集 (相当于把两个集合合并了没有重复的元素)
set1 - set2求set1和set2的差集(项在set1,但不在set2中,简单来说就是说set1中有的set2他没有,然后返回set1中set2没有的)