题目
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.
答案
跟word pattern II的思路完全一样,而且更简单不需要backtracking
class Solution {
public List<String> findAndReplacePattern(String[] words, String pattern) {
List<String> list = new ArrayList<>();
for(int i = 0; i < words.length; i++) {
Map<Character, Character> map = new HashMap<>();
Set<Character> taken = new HashSet<>();
boolean matched = true;
if(words[i].length() == pattern.length()) {
for(int j = 0; j < words[i].length(); j++) {
char pc = pattern.charAt(j);
char wc = words[i].charAt(j);
Character mapping = map.get(pc);
if(mapping == null) {
if(taken.contains(wc)) {
matched = false;
break;
}
taken.add(wc);
map.put(pc, wc);
}
else {
if(wc != mapping) {
matched = false;
break;
}
}
}
if(matched) list.add(words[i]);
}
}
return list;
}
}
网友评论