思路:首先判断两个字符串长度是否相等,不相等直接False;
利用哈希表记录其中一个字符串中每个字母出现的次数,再用循环判断第二个字符串中的字母是否在哈希表中,若存在,哈希表中该字母次数减1,直到循环结束,若哈希表不为空,则失败
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dict={}
if len(s)!=len(t):
return False
for i in s:
if i in dict:
dict[i]+=1
else:
dict[i]=1
for j in t:
if j in dict:
dict[j]-=1
for i in s:
if dict[i]!=0:
return False
return True
思路:我的思路用的数组,遍历其中一个列表,判断元素是否在另一个列表中,若存在且结果数组中没有该元素,将该元素加入结果数组
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
rs=[]
for i in nums1:
if i in nums2 and i not in rs:
rs.append(i)
return rs
思路:定义一个集合来存放过程结果,如果求和出现在过程结果中,则说明陷入无限循环
class Solution(object):
def get_sum(self,n):
new_sum=0
while n:
n,r=divmod(n,10)
new_sum+=r*r
return new_sum
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
record =set()
while True:
n=self.get_sum(n)
if n==1:
return True
elif n in record:
return False
else:
record.add(n)
思路:定义一个哈希表,遍历数组,如果目标值减去当前数在哈希表中,则返回哈希表中的值的位置以及当前值的位置;若不存在,则将当前值以及位置存入哈希表中
class Solution:
def twoSum(self,nums,target):
dic={}
for i,n in enumerate(nums):
cp=target-n
if cp in dic:
return [dic[cp],i]
else:
dic[n]=i
return []