You have a list of words
and apattern
, and you want to know which words inwords
matches the pattern.
A word matches the pattern if there exists a permutation of lettersp
so that after replacing every letterx
in the pattern withp(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 inwords
that match the given pattern.
You may return the answer in any order.
class Solution {
public List<String> findAndReplacePattern(String[] words, String pattern) {
List<String> res = new ArrayList<>();
if(words == null || words.length == 0)
return res;
for(String word: words) {
if(match(word, pattern))
res.add(word);
}
return res;
}
public boolean match(String word, String pattern) {
if(pattern.length() != word.length())
return false;
HashMap<Character, Character> map1 = new HashMap<>();
HashMap<Character, Character> map2 = new HashMap<>();
for(int i = 0; i < pattern.length(); i++) {
char c1 = pattern.charAt(i);
char c2 = word.charAt(i);
if(map1.containsKey(c1) && !map2.containsKey(c2))
return false;
if(!map1.containsKey(c1) && map2.containsKey(c2))
return false;
if(map1.containsKey(c1) && map2.containsKey(c2)) {
if(c1 != map2.get(c2) || c2 != map1.get(c1))
return false;
} else {
map1.put(c1, c2);
map2.put(c2, c1);
}
}
return true;
}
}