890. Find and Replace Pattern - Medium
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 <= words.length <= 50
1 <= pattern.length = words[i].length <= 20
intuition:把word和pattern对应的字符存进map,同一个key只能有一个value(否则false),同一个value也只能对应一个key(否则false),检查两遍
1,对于每一个word和pattern,首先遍历字符串,把对应字符<word[i], pattern[i]>存入hash table中,这期间如果一个key对应多个value,直接返回false
2,check map中存的字母是否distinct:用一个boolean数组表示26个小写字母,如果当前字母没有见过,标记为true;如果当前字母见过,直接返回false
time = O(N * L), space = O(L), N = words.length, L = pattern.length()
class Solution { public List<String> findAndReplacePattern(String[] words, String pattern) { List<String> res = new ArrayList<>(); for(String word : words) { if(match(word, pattern)) { res.add(word); } } return res; } private boolean match(String word, String pattern) { Map<Character, Character> map = new HashMap<>(); for(int i = 0; i < word.length(); i++) { char w = word.charAt(i); char p = pattern.charAt(i); if(!map.containsKey(w)) { map.put(w, p); } else if(map.get(w) != p) { return false; } } boolean[] seen = new boolean[26]; for(Map.Entry<Character, Character> entry : map.entrySet()) { char val = entry.getValue(); if(seen[val - 'a']) { return false; } seen[val - 'a'] = true; } return true; } }