leetcode(力扣) 890. 查找和替换模式 (sao操作)
时间:2022-10-31 06:00:01
文章目录
- 题目描述
- 思路分析
- 完整代码
题目描述
你有一个单词列表 words 和一个模式 pattern,你想知道 words 哪些单词与模式相匹配。
若有字母排列 p ,模式中的每个字母 x 替换为 p(x) 之后,我们得到了所需的单词,所以单词与模式相匹配。
(回想起来,字母的排列是从字母到字母的双射:每个字母映射到另一个字母,没有两个字母映射到同一个字母。
返回 words 单词列表模式的单词列表。
您可以按任何顺序返回答案。
示例:
输入:words = [“abc”,“deq”,“mee”,“aqq”,“dkd”,“ccc”], pattern = “abb”
输出:[“mee”,“aqq”]
解释:
“mee” 由于有排列,与模式匹配 {a -> m, b -> e, …}。
“ccc” 因为 {a -> c, b -> c, …} 不是排列。
因为 a 和 b 映射到同一个字母。
思路分析
看到这个问题后,我直接想用两个哈希表或一个哈希表映射来做。后来,我发现评论区有一个奇怪的老板。zip所以我来效仿一下。
假设有:words = [“mee”,], pattern = “abb”
则
list(zip(words,pattern)后有:
[(‘m’, ‘a’), (‘e’, ‘b’), (‘e’, ‘b’)]
去重之后
set(zip(words,pattern)后有:
{(‘m’, ‘a’), (‘e’, ‘b’)}
看有这些都应该被理解,只要相应映射去重后的长度 = 单词去重长度 = 模式去重长度 所以这两种模式是一样的。
完整代码
class Solution: def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]: return [i for i in words if len(set(i)) == len(set(pattern)) == len(set(zip(i,pattern)))] # res = [] # for i in words: # if len(set(i)) == len(set(pattern)) == len(set(zip(i,pattern))): # res.append(i) # print(res) # return res