题目链接🔗:有效的字母异位词
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
示例 1: 输入: s = "anagram", t = "nagaram" 输出: true
示例 2: 输入: s = "rat", t = "car" 输出: false
说明: 你可以假设字符串只包含小写字母。
思路:做一个长度为26的数组,数组的本质也是哈希表,key为数组的索引,value为数组的值。
先遍历自字符串s做累加,在遍历t做减法。最终遍历完之后,数组为0则返回true,若不为零,则返回false
正确代码✅:
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
record = [0] * 26
for i in s:
record[ord(i) - ord("a")] +=1
for i in t:
record[ord(i) - ord("a")] -=1
for i in range(26):
if record[i] != 0:
return False
return True
题目链接🔗:两个数组的交集
题意:给定两个数组,编写一个函数来计算它们的交集
思路:新建一个集合set,遍历数组nums1,判断遍历的元素是否在另一个数组nums2内,如果在放入新建的集合set内,最后返回set
正确代码✅:
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
set_list = set()
for i in nums1:
if i in nums2:
set_list.add(i)
return list(set_list)