当前位置:网站首页>每日一题-890. 查找和替换模式
每日一题-890. 查找和替换模式
2022-06-12 16:16:00 【程序猿不脱发2】
题目:
你有一个单词列表 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
java代码:
class Solution {
public List<String> findAndReplacePattern(String[] words, String pattern) {
List<String> ans = new ArrayList<String>();
for (String word : words) {
if (match(word, pattern) && match(pattern, word)) {
ans.add(word);
}
}
return ans;
}
public boolean match(String word, String pattern) {
Map<Character, Character> map = new HashMap<Character, Character>();
for (int i = 0; i < word.length(); ++i) {
char x = word.charAt(i), y = pattern.charAt(i);
if (!map.containsKey(x)) {
map.put(x, y);
} else if (map.get(x) != y) { // word 中的同一字母必须映射到 pattern 中的同一字母上
return false;
}
}
return true;
}
}
边栏推荐
- Reprise de Google net
- The C Programming Language(第 2 版) 笔记 / 8 UNIX 系统接口 / 8.4 随机访问(lseek)
- Development status of China's pig breeding industry in 2021 and comparative analysis of key enterprises: 671million pigs were sold [figure]
- 面试:hashCode()和equals()
- 面试:了解装箱和拆箱操作吗?
- [automation] kolla Based Automated Deployment CEPH cluster
- 国产CPLD中AG1280Q48进行开发的实践之一:思路分析
- RTOS rt-thread裸机系统与多线程系统
- acwing 798二维差分(差分矩阵)
- acwing 801. 二进制中1的个数(位运算)
猜你喜欢

acwing 803. Interval merging

鼻孔插灯,智商上升,风靡硅谷,3万就成

从斐波那契数列求和想到的俗手、本手和妙手

The small flying page is upgraded to be intelligent and the bug repair is faster

超详细干货!Docker+PXC+Haproxy搭建高可用强一致性的MySQL集群

< 山东大学软件学院项目实训 > 渲染引擎系统——点云处理(十)

写代码也有本手俗手之分,而我们要善于发现妙手!

acwing 798二维差分(差分矩阵)

Batch --04--- moving components

acwing 803. 区间合并
随机推荐
What is JUC in high concurrency programming
Scanpy (VI) analysis and visualization of spatial transcriptome data
面试:hashCode()和equals()
Multimix:从医学图像中进行的少量监督,可解释的多任务学习
面试:什么是浅拷贝、深拷贝?
Office VR porn, coquettish operation! The father of Microsoft hololens resigns!
From K-means to capsule
Go Net Library (to be continued)
Chapter I linear table
Tensorflow function: tf nn. in_ top_ k()
Step by step to create a trial version of ABAP program containing custom screen
[automation] kolla Based Automated Deployment CEPH cluster
位运算例题(待续)
Example of bit operation (to be continued)
< 山东大学软件学院项目实训 > 渲染引擎系统——基础渲染器(三)
[tool recommendation] personal local markdown knowledge map software
Redis General Command
Solution to idea Chinese prism garbled code error -- console Chinese output prism garbled code
The small flying page is upgraded to be intelligent and the bug repair is faster
Thread pool execution process