当前位置:网站首页>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;
}
边栏推荐
- 程序员自由工作的三大痛点?一文教你统统解决
- 【板栗糖GIS】wps—如何查看表格中的超链接
- 03-树3 Tree Traversals Again(树的遍历)
- 毕业论文文献综述写作技巧,超级详细!
- 5 V booster charge 8.4 V chip
- One of the uses of linkedlist: Get the address of the structure variable through the address of the structure member
- 仿Modbus消息帧进行通信
- C语言操作符详解(1)
- OPEN数据 | 新库上线 | CnOpenDataA股上市公司社会责任报告数据
- 一文理解分布式开发中的服务治理
猜你喜欢
随机推荐
D. Rain(思维/线性代数/差分数组)
GBASE 8s 如何查看 sbspace 中的可用空间
GBASE 8s PAM插入式身份验证模块
tkinter绘制组件(31)——支点标题
Verilog 加法器设计
Huawei Enjoy 50 Pro evaluation: HarmonyOS blessing is smoother and safer
仿Modbus消息帧进行通信
品牌广告投放平台的中台化应用与实践
杨辉三角的各种输出:
Advanced Mathematics (Seventh Edition) Tongji University Exercises 3-8 Individual Answers
VSCode 插件大全
How to implement your personal knowledge base?
Add obsolete flag to pdf
给pdf添加已作废标识
CNCF Keith Chan:分布式云时代,云原生社区的发展与趋势
小程序微信定位不准
Advanced Mathematics (Seventh Edition) Tongji University Exercises 3-7 Individual Answers
【板栗糖GIS】arcmap—标注太长,如何换行显示
Xshell 7 提示 “要继续使用此程序,您必须应用最新的更新或使用新版本”
【Verilog 设计】Verilog 实现偶数、奇数分频和任意小数分频









