思路:使用哈希对比,标记两字符串出现的次数,第一个+1,第二-1,如果最后都为0,则相同。
总结:脑子空空,第一次刷哈希的,还是有点不是很懂,全部的思路以及总结需细盘下。
代码:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
record = [0] * 26
# 遍历s
for i in s:
record[ord(i) - ord("a")] += 1 # 把结果放到数组中 +1
for i in t:
record[ord(i) - ord("a")] -= 1 # 把结果放到数组中 +1
for i in range(26):
if record[i] != 0: # 数组中有元素不为0,说明两个字符串不相等
return False
return True
def isAnagram1(self, s: str, t: str) -> bool:
# 使用defaultdict
if len(s) != len(t):
return False
dic = defaultdict(int)
for i in s:
dic[i] += 1
for i in t:
dic[i] -= 1
for val in dic.values():
if val != 0:
return False
return True
代码:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
# 一个数组为空,交集为空
if not nums1 or not nums2:
return []
# 初始化列表
hash = {}
for i in nums1: # key为nums1数组中的数,value为值
if not hash.get(i):
hash[i] = 1
res = []
# 如果nums2中的数出现在哈希表中,对应数放入结果列表,对应value值置为0
for j in nums2:
if hash.get(j):
res.append(j)
hash[j] = 0
return res
三、202. 快乐数
代码 :
# 求正整数 num每个位置上数字的平方和
def getNext(self, num):
happy_num = 0
while num:
happy_num += (num % 10) ** 2
num = num // 10
return happy_num
def isHappy(self, n: int) -> bool:
# 记录过程
mid = set()
while True:
n = self.getNext(n) # 把当前数替换为每个位置上的数字的平方和
if n == 1:
return True
if n in mid: # 如果替换后的数再次出现,则是陷入了循环,不是快乐数
return False
else:
mid.add(n)
四、1. 两数之和
代码:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = dict()
for index, value in enumerate(nums):
if target - value in dic: # 遍历寻找是否有匹配的key
return [dic[target - value], index] # 返回两个数的下标
dic[value] = index # 没找到,则保存访问过的元素和下标
return []