一、 题目
1. 题目描述
你有一个单词列表 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 映射到同一个字母。
提示:
1 <= words.length <= 50
1 <= pattern.length = words[i].length <= 20
Related Topics
- 数组
- 哈希表
- 字符串
- 👍 168
- 👎 0
二、 解题报告
1. 思路分析
用两个哈希表,互相映射字母,如果检测到当前字符与之前映射过的字符冲突,则无法匹配。
2. 复杂度分析
最坏时间复杂度O(nc)*
3. 代码实现
哈希表
。
class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
n = len(pattern)
ans = []
for word in words:
ab = {}
ba = {}
for i in range(n):
a = word[i]
b = pattern[i]
if (a in ab and ab[a] != b) or (b in ba and ba[b] != a):
break
else :
ab[a] = b
ba[b] = a
else:
ans.append(word)
return ans
三、 本题小结
- 一道哈希表题目。