forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind-and-replace-pattern.cpp
More file actions
35 lines (33 loc) · 932 Bytes
/
find-and-replace-pattern.cpp
File metadata and controls
35 lines (33 loc) · 932 Bytes
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
26
27
28
29
30
31
32
33
34
35
// Time: O(n * l)
// Space: O(1)
class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
vector<string> result;
for (const auto& word: words) {
if (match(word, pattern)) {
result.emplace_back(word);
}
}
return result;
}
private:
bool match(const string& word, const string& pattern) {
unordered_map<char, char> lookup;
unordered_set<char> char_set;
for (int i = 0; i < word.length(); ++i) {
const auto& c = word[i], &p = pattern[i];
if (!lookup.count(c)) {
if (char_set.count(p)) {
return false;
}
char_set.emplace(p);
lookup[c] = p;
}
if (lookup[c] != p) {
return false;
}
}
return true;
}
};