for i in pattern: if i notin tbl: tbl[i] = c c += 1 ptn.append(tbl[i])
defmatch(w): tbl.clear() c = 0 for i inrange(len(w)): if w[i] notin tbl: tbl[w[i]] = c c += 1 if tbl[w[i]] != ptn[i]: returnFalse returnTrue
# print(ptn) returnfilter(match, words)
思路 2,双射(bijection)
用两个哈希表分别映射 pattern 字符和目标字符,检查映射结果是否一致。
用 m1 储存目标字符到 pattern 字符的映射,比如字符 x -> a;
用 m2 储存 pattern 字符到目标字符的映射,比如字符 a -> x;
作为判断条件,当下面条件任意一个满足,则表示目标字符与 pattern 不匹配:
m1 中字符 x 对应的字符与当前 pattern 相对下标的字符不匹配;或,
m2 中字符 a 对应的字符与当前目标字符串相对下标的字符不匹配。
如果到最后一个字符依然匹配,则目标字符匹配 pattern。
classSolution{ private Map<Character, Character> m1 = new HashMap<>(); private Map<Character, Character> m2 = new HashMap<>(); public List<String> findAndReplacePattern(String[] words, String pattern){ List<String> ans = new ArrayList<>(); for (String w : words) { if (match(w, pattern)) ans.add(w); } return ans; } privatebooleanmatch(String w, String ptn){ m1.clear(); m2.clear(); for (int i = 0; i < w.length(); i++) { char c = w.charAt(i); char p = ptn.charAt(i); if (!m1.containsKey(c)) m1.put(c, p); if (!m2.containsKey(p)) m2.put(p, c); if (m1.get(c) != p || m2.get(p) != c) returnfalse; } returntrue; } }
classSolution{ private Map<Character, Character> m1 = new HashMap<>(); public List<String> findAndReplacePattern(String[] words, String pattern){ List<String> ans = new ArrayList<>(); for (String w : words) { if (match(w, pattern)) ans.add(w); } return ans; } privatebooleanmatch(String w, String ptn){ m1.clear(); for (int i = 0; i < w.length(); i++) { char c = w.charAt(i); char p = ptn.charAt(i); if (!m1.containsKey(c)) m1.put(c, p); if (m1.get(c) != p) returnfalse; }
boolean[] test = newboolean[26]; for (char v : m1.values()) { if (test[v - 'a']) { returnfalse; } else { test[v - 'a'] = true; } } returntrue; } }
/** * @param {string[]}words * @param {string}pattern * @return {string[]} */ var findAndReplacePattern = function (words, pattern) { return words.filter((w) => { const map = {}; for (let i = 0; i < w.length; i++) { const c = w.charAt(i), p = pattern.charAt(i); if (!map[c]) map[c] = p; if (p !== map[c]) returnfalse; } const test = []; for (let v ofObject.values(map)) { if (test.indexOf(v) > -1) { returnfalse; } else { test.push(v); } } returntrue; }); };