本题主要是解决在一串单词中,找出字母符合对应排列的单词的集合
其实不是很难,但自己一开始自己想复杂了
第一次提交的代码
class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
if pattern == "":
return words
# 先求pattern中每个字母对应的位置集合、每个位置对应的字母
l = len(pattern)
dic_pattern = {}
dic_position = {}
for i in range(l):
s = pattern[i]
if s not in dic_pattern.keys():
dic_pattern[s] = [i]
else:
dic_pattern[s].append(i)
dic_position[i] = s
# 判断每个单词是否符合模式字典
res = []
for word in words:
if len(word) != l:
continue
dic_word = {}
f = True
for i in range(l):
w = word[i]
if w not in dic_word.keys():
dic_word[w] = [i]
else:
dic_word[w].append(i)
s = dic_position[i]
if len(dic_pattern[s]) < len(dic_word[w]) :
f = False
break
else:
for j in range(len(dic_word[w])):
if dic_word[w][j] != dic_pattern[s][j]:
f = False
break
if not f:
break
if f:
res.append(word)
return res
我也不知道为什么会想得这么绕这么复杂
果然早起值班脑子不清醒(⊙v⊙)
回实验室第一次提交以后发现只比2%的人快
突然就想到了直接用两个字典来回判断的方法
第二次提交的代码,其实这题思路很简单:
class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
if pattern == "":
return words
l = len(pattern)
res = []
for word in words:
if len(word) != l:
continue
dic = {}
dic_pattern = {}
f = True
for i in range(l):
if word[i] not in dic.keys():
dic[word[i]] = pattern[i]
elif dic[word[i]] != pattern[i]:
f = False
break
if pattern[i] not in dic_pattern.keys():
dic_pattern[pattern[i]] = word[i]
elif dic_pattern[pattern[i]] != word[i]:
f = False
break
if f:
res.append(word)
return res