You have a list of `words` and a `pattern`, and you want to know which words in `words` matches the pattern.

A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.

(Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.)

Return a list of the words in words that match the given pattern.

You may return the answer in any order.

Example 1:

Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
Output: ["mee","aqq"]
Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}.
"ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation,
since a and b map to the same letter.

Note:

  • 1 <= words.length <= 50
  • 1 <= pattern.length = words[i].length <= 20

这道题给了我们一个字符串数组 words,还有一个 pattern 单词,问 words 数组中的单词是否满足 pattern 的模式,并给了一个例子。比如 pattern 是 abb 的话,表示后两个字母是相同的,比如 mee 和 aqq,那么一个很直接的想法就是建立每个单词 word 和 pattern 中每个字符之间的映射,比如 mee->abb 的话,就是 m->a, e->b,在建立映射之前要判断,若已经存在了该映射,且映射值不是当前 pattern 中的对应字符时,就是无法匹配的,比如 mm 和 ab,在第一次建立了 m->a 的映射,当遍历到第二个m的时候,发现m的映射已经存在,但不是b,就不能再建立 m->b 的映射,则表示无法匹配。分析到这里,你可能感觉没啥问题,但其实我们忽略一种情况,word 和 pattern 中的每个字符必须是一一对应的,任何一个方向的多对一都是不行了,比如 mn 和 aa,刚开始建立了 m->a 的映射,遍历到n的时候,发现没有n的映射,此时也不能建立 n->a 的映射,因为 pattern 中的a已经被占用了,所以还需要一个 HashMap 来建立反方向的映射,只有两个 HashMap 中都不存在的,才能建立映射,只要有一个已经存在了,直接 break 掉。在 for 循环结束后,看是否已经到达了 word 的末尾,没有提前 break 掉的话,就将 word 加入结果 res 中即可,参见代码如下:


解法一:

class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
vector<string> res;
for (string word : words) {
unordered_map<char, char> w2p, p2w;
int i = 0, n = word.size();
for (; i < n; ++i) {
if (w2p.count(word[i]) && w2p[word[i]] != pattern[i]) break;
w2p[word[i]] = pattern[i];
if (p2w.count(pattern[i]) && p2w[pattern[i]] != word[i]) break;
p2w[pattern[i]] = word[i];
}
if (i == n) res.push_back(word);
}
return res;
}
};

我们也可以不用 HashMap,改用两个长度为 26 的数组,因为这道题貌似默认都是小写字母,唯一麻烦一点的就是要把字母减去 'a' 来转为对应的坐标,还有一点跟上面解法不同的地方就是,字母是跟起坐标位置加1来建立映射(加1的原因是默认值是0,而当 i=0 时为了区分默认值,就要加1),因为两个字母都跟一个特定的值相等,其实也等价于这两个字母之间建立的映射(a->c, b->c => a->b)。整体思路还是没啥不同的,参见代码如下:


解法二:

class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
vector<string> res;
for (string word : words) {
vector<int> w(26), p(26);
int i = 0, n = word.size();
for (; i < n; ++i) {
if (w[word[i] - 'a'] != p[pattern[i] - 'a']) break;
w[word[i] - 'a'] = p[pattern[i] - 'a'] = i + 1;
}
if (i == n) res.push_back(word);
}
return res;
}
};

在论坛上又看到了一种解法,这种解法相当于把所有的单词都转为了一种特定的模式,具体来说,就是用一个 HashMap,建立每个字母跟其之前出现过的字母种类个数之前的映射,比如 mee->011,aqq->011,这样相同的模式映射的值是一样的,具体的做法是若当前字母没有出现过,则建立和当前 HashMap 中的映射个数之间的映射,是一种很巧妙的设计思路,只不过最后又给每个数字加上了 'a',转为了字母的 pattern,即 mee->abb,aqq->abb,参见代码如下:


解法三:

class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
vector<string> res;
for (string word : words) {
if (helper(word) == helper(pattern)) res.push_back(word);
}
return res;
}
string helper(string word) {
unordered_map<char, int> m;
for (char c : word) {
if (!m.count(c)) m[c] = m.size();
}
for (int i = 0; i < word.size(); ++i) word[i] = 'a' + m[word[i]];
return word;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/890

类似题目:

Repeated Substring Pattern

132 Pattern

Word Pattern II

Word Pattern

参考资料:

https://leetcode.com/problems/find-and-replace-pattern/

https://leetcode.com/problems/find-and-replace-pattern/discuss/161266/JAVA-3ms-Clear-Code

https://leetcode.com/problems/find-and-replace-pattern/discuss/161288/C%2B%2BJavaPython-Normalise-Word

[LeetCode All in One 题目讲解汇总(持续更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)

[LeetCode] 890. Find and Replace Pattern 查找和替换模式的更多相关文章

  1. Leetcode 890. Find and Replace Pattern

    把pattern映射到数字,也就是把pattern标准化. 比如abb和cdd如果都能标准化为011,那么就是同构的. class Solution: def findAndReplacePatter ...

  2. 890. Find and Replace Pattern - LeetCode

    Question 890. Find and Replace Pattern Solution 题目大意:从字符串数组中找到类型匹配的如xyy,xxx 思路: 举例:words = ["ab ...

  3. LC 890. Find and Replace Pattern

    You have a list of words and a pattern, and you want to know which words in words matches the patter ...

  4. 【LeetCode】890. Find and Replace Pattern 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典+set 单字典 日期 题目地址:https:/ ...

  5. [Swift]LeetCode890. 查找和替换模式 | Find and Replace Pattern

    You have a list of words and a pattern, and you want to know which words in words matches the patter ...

  6. leetcode 890. 查找和替换模式 Python

    用模式的每个字母去当做key对应单词列表的每个字母value, 如果放进dict之前检测到key已经存在,就检测Word[i][j]是否是和已经存在的value一致,不一致就代表不匹配,break检查 ...

  7. 890. Find and Replace Pattern找出匹配形式的单词

    [抄题]: You have a list of words and a pattern, and you want to know which words in words matches the ...

  8. [LeetCode] Find And Replace in String 在字符串中查找和替换

    To some string S, we will perform some replacement operations that replace groups of letters with ne ...

  9. 如何使用Replace Pioneer批量查找和替换并提取指定字符串

    1 我们查看源代码之后获得的网页文件如下图所示,一般都是href="/p-286018571.html"我们只要能提取到所有的"/p-XXXXXXXX.html" ...

随机推荐

  1. Windows7运行python3,提示缺少api-ms-win-crt-runtime-l1-1.0.dll

    一.实验环境 1.Windows7x64_SP1 二.操作步骤 2.1 python官网下载python3.6后,安装.运行,提示如下错误: 2.2 解决方式 去微软官网下载安装:KB2999226补 ...

  2. mysql 创建用户, 分配权限, 删除用户

    通过create user 命令来创建用户, 有两种方式:(只介绍通过 create user 命令, 直接往user表中插入数据的方式,这里就不说了) 创建用户的同时, 指定用户可登录的主机和密码 ...

  3. asp.net core系列 63 领域模型架构 eShopOnWeb项目分析 上

    一.概述 本篇继续探讨web应用架构,讲基于DDD风格下最初的领域模型架构,不同于DDD风格下CQRS架构,二者架构主要区别是领域层的变化. 架构的演变是从领域模型到CQRS,  一开始DDD是用领域 ...

  4. 【洛谷5437】【XR-2】约定(拉格朗日插值)

    [洛谷5437][XR-2]约定(拉格朗日插值) 题面 洛谷 题解 首先发现每条边除了边权之外都是等价的,所以可以考虑每一条边的出现次数. 显然钦定一条边之后构成生成树的方案数是\(2*n^{n-3} ...

  5. 【LOJ#3144】[APIO2019]奇怪装置(数论)

    [LOJ#3144][APIO2019]奇怪装置(数论) 题面 LOJ 题解 突然发现\(LOJ\)上有\(APIO\)的题啦,赶快来做一做. 这题是窝考场上切了的题嗷.写完暴力之后再推了推就推出正解 ...

  6. redis 面试问题问答Top 10

    1)什么是Redis? English:Redis is an open source (BSD licensed), in-memory data structure store, used as ...

  7. laravel he stream or file "..laravel-2019-02-14.log" could not be opened: failed to open stream: Permission denied

    错误:The stream or file "/var/www/jianshu/storage/logs/laravel-2019-02-14.log" could not be ...

  8. 浅析java线程和OS线程的关系

    探究java线程和OS线程之间的联系 一.准备工作 1.查看linux创建线程的方法    man pthread_create 根据man的配置可知,pthread_create会创建一个线程,这个 ...

  9. java--set,Collections,map

    set 特点: 无序, 不允许重复 没有索引 Set<String> set = new HashSet<String>(); set.add("hello" ...

  10. 英语四6级CET6资料大学六级单词

    ambient a.周围的,包围着的 ambiguous a.模棱两可的:分歧的 ambitious a.有雄心的:热望的 ample a.足够的:宽敞的 amplitude n.广大:充足:振幅 a ...