890. 查找和替换模式

本题主要是解决在一串单词中,找出字母符合对应排列的单词的集合

其实不是很难,但自己一开始自己想复杂了

第一次提交的代码

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值