作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/find-and-replace-pattern/description/

题目描述

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. 1 <= words.length <= 50
  2. 1 <= pattern.length = words[i].length <= 20

题目大意

我觉得应该把题目中的permutation理解为“映射”更为合适。

这样的话,题目意思就是找出words中所有满足映射关系的单词。映射关系由pattern给出,即要求words中的单词和pattern中的每个字符的对应关系应该完全一致。

解题方法

字典+set

既然考到映射,那么应该是使用HashMap来搞定,直接把映射一一的放入map中,如果出现过这个映射的话,就看新的对应关系和原来的映射是否相同。

代码中使用了set,这个set很重要,因为这个保证了不会出现ccc对应abb这种。

注意题目中给出了一个细节,就是words里面的每个word都和pattern长度相同,省去了判断长度的过程。

代码如下:

class Solution(object):
def findAndReplacePattern(self, words, pattern):
"""
:type words: List[str]
:type pattern: str
:rtype: List[str]
"""
ans = []
set_p = set(pattern)
for word in words:
if len(set(word)) != len(set_p):
continue
fx = dict()
equal = True
for i, w in enumerate(word):
if w in fx:
if fx[w] != pattern[i]:
equal = False
break
fx[w] = pattern[i]
if equal:
ans.append(word)
return ans

单字典

如果使用单字典,需要判断word向pattern的映射和pattern向word的映射。这个代码就没有什么好说的了。

Python代码如下:

class Solution(object):
def findAndReplacePattern(self, words, pattern):
"""
:type words: List[str]
:type pattern: str
:rtype: List[str]
"""
res = []
for word in words:
if len(word) != len(pattern): continue
d = dict()
isMatch = True
for i, c in enumerate(pattern):
if c in d:
if d[c] != word[i]:
isMatch = False
break
d[c] = word[i]
d = dict()
for i, c in enumerate(word):
if c in d:
if d[c] != pattern[i]:
isMatch = False
break
d[c] = pattern[i]
if isMatch:
res.append(word)
return res

C++代码如下:

class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
vector<string> res;
for (string& word : words) {
bool isMatch = true;
map<char, char> d;
for (int i = 0; i < word.size(); i++) {
if (d.count(word[i])) {
if (d[word[i]] != pattern[i]) {
isMatch = false;
break;
}
}
d[word[i]] = pattern[i];
}
d.clear();
for (int i = 0; i < word.size(); i++) {
if (d.count(pattern[i])) {
if (d[pattern[i]] != word[i]) {
isMatch = false;
break;
}
}
d[pattern[i]] = word[i];
}
if (isMatch) res.push_back(word);
}
return res;
}
};

日期

2018 年 8 月 24 日 —— Keep fighting!
2018 年 11 月 5 日 —— 打了羽毛球,有点累
2018 年 12 月 2 日 —— 又到了周日

【LeetCode】890. Find and Replace Pattern 解题报告(Python & C++)的更多相关文章

  1. [LeetCode] 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 ...

  2. 【LeetCode】459. Repeated Substring Pattern 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 遍历子串 日期 [LeetCode] 题目地址:ht ...

  3. Leetcode 890. Find and Replace Pattern

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

  4. 【LeetCode】206. Reverse Linked List 解题报告(Python&C++&java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 递归 日期 [LeetCode] 题目地址:h ...

  5. 【LeetCode】654. Maximum Binary Tree 解题报告 (Python&C++)

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

  6. 【LeetCode】784. Letter Case Permutation 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 回溯法 循环 日期 题目地址:https://leet ...

  7. 【LeetCode】456. 132 Pattern 解题报告(Python)

    [LeetCode]456. 132 Pattern 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fu ...

  8. 890. Find and Replace Pattern - LeetCode

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

  9. 【LeetCode】468. Validate IP Address 解题报告(Python)

    [LeetCode]468. Validate IP Address 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: h ...

随机推荐

  1. (转载)SQL Server 2008 连接JDBC详细图文教程

    点评:SQL Server 2008是目前windows上使用最多的sql数据库,2008的安装机制是基于framework重写的,特点是非常耗时间SQL Server 2008是目前windows上 ...

  2. Kubernetes-存储(一)

    前言 本篇是Kubernetes第十二篇,大家一定要把环境搭建起来,看是解决不了问题的,必须实战. Kubernetes系列文章: Kubernetes介绍 Kubernetes环境搭建 Kubern ...

  3. 前端页面存放token

    //本地缓存,记录token function set(type, value) { localStorage.setItem(type, value); } function get(type) { ...

  4. ORACLE profile含义,修改,新增

    profiles文件是口令和资源限制的配置集合,包括CPU的时间.I/O的使用.空闲时间.连接时间.并发会话数量.密码策略等对于资源的使用profile可以做到控制会话级别或语句调用级别.oracle ...

  5. jenkins之代码部署回滚脚本

    #!/bin/bash DATE=`date +%Y-%m-%d_%H-%M-%S` METHOD=$1 BRANCH=$2 GROUP_LIST=$3 function IP_list(){ if ...

  6. Advanced C++ | Conversion Operators

    In C++, the programmer abstracts real world objects using classes as concrete types. Sometimes it is ...

  7. clickhouse客户端使用

    测试初始化 clickhouse-client -m create database if not exists test; use test; drop table test; create tab ...

  8. POST/GET请求中RequestBody和RequestParam的应用场景

    POST请求时 @RequestBody --> JSON字符串部分 @RequestParam --> 请求参数部分 application/json格局图   图一.png form- ...

  9. Shell脚本定期清空大于1G的日志文件

    一个关于如何在指定文件大于1GB后,自动删除的问题. 批处理代码如下: #!/bin/bash # 当/var/log/syslog大于1GB时 # 自动将其备份,并清空 # 注意这里awk的使用 i ...

  10. SQL 父子表,显示表中每条记录所在层级

    1.sqlserer 中有一张父子关系表,表结构如下: CREATE TABLE [dbo].[testparent]( [ID] [int] IDENTITY(1,1) NOT NULL, [nam ...