本题的思路是建立一个哈希表,将字母和字符串之间一一对应
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
ch2word=dict()
word2ch=dict()
words=s.split() # 以空格为分隔符分割字符串
if len(pattern)!=len(words):
return False
for ch,word in zip(pattern,words):
if (word in word2ch and word2ch[word]!=ch) or (ch in ch2word and ch2word[ch]!=word):
return False
ch2word[ch]=word
word2ch[word]=ch
return True
重点:字典还可以好几个维度
class Solution:
def findShortestSubArray(self, nums: List[int]) -> int:
# 利用哈希表找出每个元素的度
mp=dict()
# mp 是三维数组
# 0:代表元素出现的次数
# 1:第一次出现的索引
# 2:最后一次出现的索引
for i,num in enumerate(nums):
if num in mp:
mp[num][0]+=1
mp[num][2]=i
else:
mp[num]=[1,i,i]
# 计算得到了数组的度和元素的起始位
max_degree=0
min_length=inf
for degree, begin, end in mp.values():
if degree>max_degree:
max_degree=degree
min_length=end-begin+1
if degree==max_degree:
min_length=min(min_length,end-begin+1)
return min_length
本题目需要记住的重点是lamada的用法。
class Solution:
def longestWord(self, words: List[str]) -> str:
# 按照字符串的长度和字符串的字序排序
words.sort(key=lambda x: (-len(x),x ), reverse=True)
longest =""
candicates=[""]
for word in words:
if word[:-1] in candicates:
longest=word
candicates.append(word)
return longest
"""
lamada 是匿名函数,一行表达式表达函数的功能
本题中的lamada x:(-len(X,X))是对元组进行排序
"""
用到了上述中的lambda
class Solution:
def frequencySort(self, nums: List[int]) -> List[int]:
count=Counter(nums)
return sorted(nums,key=lambda item:(-count[item],item),reverse=True)
这道题给我的难度是如何判断只需要交换一次就能和goal相等,如果字符串和goal字符串相等,就看字符串中是否有重复字符,如果有的话,交换重复字符就可以;如果字符串不相等的话,那就判断是不是只有一对字符位置不对,并且位置不对的地方能够对应的上。
class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
# 记录index,
# 不能利用count来简单的判断这个题
# 交换两个index可以使两个字符串相等
if len(s)!=len(goal):
return False
elif s==goal:
if len(set(s))<len(goal): #代表有重复的字符
return True
else:
return False
diff=[(a,b) for a,b in zip(s,goal) if a!=b]
return len(diff) == 2 and diff[0][0] == diff[1][1] and diff[0][1] == diff[1][0]
这道题的思路是巧合的将两个字典相加了,相加以后只用取只出现一次的字符即是答案。
class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
# 返回哈希表中不同键且键值为1的序列
# 如何从字符串中建立哈希表
freq=Counter(s1.split())+Counter(s2.split())
ans=list()
for word,occ in freq.items():
if occ==1:
ans.append(word)
return ans
有一种方法是设置sort中的cmp函数,利用元组的思想,如果在列表2中,则按照列表2的顺序排序,如果不在的话,按照数字大小排序。
知识点:list.sort()仅为list设计,而sorted()函数可接收任何的迭代体
class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
# # arr2+other
# #arr1的长度一定比arr2大
# # 就像那个字典一样
# index={num:i for i,num in enumerate(arr2)}
# count=dict()
# # 计算每个字母出现的次数
# for num in arr1:
# if num in count:
# count[num]+=1
# else:
# count[num]=1
# ans=[]
# # 找到多余的数字
# other=list()
# for num in arr1:
# if num not in arr2:
# other.append(num)
# for num in index.keys():
# for i in range(count[num]):
# ans.append(num)
# #ans[len(ans):len(ans)+len(other)]=sorted(other)
# return ans.extend(sorted(other))
def mycmp(x):
return (0,rank[x]) if x in rank else (1,x)
rank={x:i for i,x in enumerate(arr2)}
arr1.sort(key=mycmp)
return arr1
class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
# arr2+other
#arr1的长度一定比arr2大
# 就像那个字典一样
index={num:i for i,num in enumerate(arr2)}
count=dict()
# 计算每个字母出现的次数
for num in arr1:
if num in count:
count[num]+=1
else:
count[num]=1
ans=[]
# 找到多余的数字
other=list()
for num in arr1:
if num not in arr2:
other.append(num)
for num in index.keys():
for i in range(count[num]):
ans.append(num)
#ans[len(ans):len(ans)+len(other)]=sorted(other)
return ans.extend(sorted(other))