[LeetCode] 890. Find and Replace Pattern
Posted CNoodle
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 890. Find and Replace Pattern相关的知识,希望对你有一定的参考价值。
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"]
Constraints:
1 <= pattern.length <= 20
1 <= words.length <= 50
words[i].length == pattern.length
pattern
andwords[i]
are lowercase English letters.
查找和替换模式。
你有一个单词列表 words 和一个模式 pattern,你想知道 words 中的哪些单词与模式匹配。
如果存在字母的排列 p ,使得将模式中的每个字母 x 替换为 p(x) 之后,我们就得到了所需的单词,那么单词与模式是匹配的。
(回想一下,字母的排列是从字母到字母的双射:每个字母映射到另一个字母,没有两个字母映射到同一个字母。)
返回 words 中与给定模式匹配的单词列表。
你可以按任何顺序返回答案。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-and-replace-pattern
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题类似205题,找同构词,思路一模一样,只不过205题问的是两个词是否互为同构词,这道题问的是 input 数组里面有哪些词跟 pattern 是同构词。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public List<String> findAndReplacePattern(String[] words, String pattern) { 3 List<String> res = new ArrayList<>(); 4 for (String word : words) { 5 if (helper(word, pattern)) { 6 res.add(word); 7 } 8 } 9 return res; 10 } 11 12 private boolean helper(String word, String pattern) { 13 HashMap<Character, Character> map = new HashMap<>(); 14 for (int i = 0; i < word.length(); i++) { 15 char w = word.charAt(i); 16 char p = pattern.charAt(i); 17 if (!map.containsKey(w)) { 18 map.put(w, p); 19 } 20 if (map.get(w) != p) { 21 return false; 22 } 23 } 24 25 boolean[] seen = new boolean[26]; 26 // 因为hashmap存的时候,key是unique的,所以value理应也是unique的 27 // 所以如果出现重复的value就说明是错的 28 for (char p : map.values()) { 29 if (seen[p - \'a\']) { 30 return false; 31 } 32 seen[p - \'a\'] = true; 33 } 34 return true; 35 } 36 }
相关题目
以上是关于[LeetCode] 890. Find and Replace Pattern的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 890. Find and Replace Pattern 查找和替换模式
LeetCode 205. Isomorphic Strings; 290. Word Pattern; 890. Find and Replace Pattern