当前位置:网站首页>leetcode 890. Find and Replace Pattern(查找和替换pattern)
leetcode 890. Find and Replace Pattern(查找和替换pattern)
2022-07-29 21:47:00 【蓝羽飞鸟】
Given a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order.
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.
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.
Example 2:
Input: words = [“a”,“b”,“c”], pattern = “a”
Output: [“a”,“b”,“c”]
返回words中和pattern匹配的单词list。
和pattern匹配是指对应的字母匹配。多个字母不能同时匹配一个字母。
思路:
可以用hashmap保存映射关系,但是看到了一个更简洁的方法。
从左到右遍历单词的字母时,如果匹配到了pattern的一个字母,
比如mee和pattern “abb”
m和a匹配,第一个e和第一个b匹配,它们的index是相同的;
那么到了后面的e时,找到它出现的第一个index, 一定和b出现的第一个index一样,
这个index相同就相当于在hashmap中找到了对应关系。
用index模拟hashmap, 这样就不需要另存一个hashmap.
public List<String> findAndReplacePattern(String[] words, String pattern) {
List<String> res = new ArrayList<>();
for(String word : words) {
if(check(word, pattern)) res.add(word);
}
return res;
}
boolean check(String word, String pattern) {
for(int i = 0; i < word.length(); i++) {
if(word.indexOf(word.charAt(i)) != pattern.indexOf(pattern.charAt(i))) return false;
}
return true;
}
边栏推荐
猜你喜欢

新库上线 | CnOpenData租赁和商务服务业工商注册企业基本信息数据

高性能数据访问中间件 OBProxy(三):问题排查和服务运维

给pdf添加已作废标识

Add a logo to the upper left corner of the picture, add time and address to the lower left corner, and wrap the line when the address reaches the specified length

【板栗糖GIS】DOS—如何在目录文件中批量建立子文件夹

文献综述的写作技巧,掌握这些技巧,效率大大提高!

给图片左上角加logo标识、左下角加时间和地址、地址到达指定长度换行

第3章业务功能开发(线索关联市场活动,插入数据并查询)

一篇关于Web3.0如何走向安全时代的说明

华为畅享50 Pro评测:HarmonyOS加持 更流畅更安全
随机推荐
程序员自由工作的三大痛点?一文教你统统解决
对不起,你很难赚到中年人的钱
防火墙——SNAT和DNAT策略的原理及应用、防火墙规则的备份和还原
新库上线 | CnOpenData国际货运代理信息数据
GBASE 8s 如何估算索引使用多少空间
GBASE 8s自定义存储过程和函数介绍
5 V booster charge 8.4 V chip
网络通信编程基础,BIO,NIO
GBASE 8s 数据库的大对象和日志备份
全球都热炸了,谷歌服务器已经崩掉了
HMS Core audio editing service audio source separation and spatial audio rendering, helping to quickly enter the world of 3D audio
获取七牛云地址文件保存到本地
【R语言】【2】绘图base和lattice和ggplot2库
C. Color the Picture(贪心/构造)
GBASE 8s 通过light scan优化查询性能
lambda表达式
十一、HikariCP源码分析之HouseKeeper
【AD】【持续更新ing】关于AD设计过程中一些小细节
"Introduction to nlp + actual combat: Chapter 7: Dataset loading in pytorch and the use of its own datasets"
Numpy array processing (2)