[LeetCode] Find and Replace Pattern

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
bool equal(string& o, string& p) {
int n = o.length();
unordered_map<char, char> mp;
unordered_set<char> us;
for(int i = 0; i < n; i++) {
if(mp.count(o[i])) {
if(mp[o[i]] != p[i]) return false;
} else {
if(us.count(p[i])) return false;
us.insert(p[i]);
mp[o[i]]=p[i];
}
}
return true;
}
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
vector<string> res;
for(auto& w : words)
if(equal(w,pattern))
res.push_back(w);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/28/PS/LeetCode/find-and-replace-pattern/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.