-
Notifications
You must be signed in to change notification settings - Fork 0
/
find-and-replace-pattern.cpp
85 lines (66 loc) · 1.84 KB
/
find-and-replace-pattern.cpp
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
* Copyright (c) 2018 Christopher Friedt
*
* SPDX-License-Identifier: MIT
*/
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// https://leetcode.com/problems/find-and-replace-pattern/
using namespace std;
class Solution {
public:
vector<string> findAndReplacePattern(vector<string> &words, string pattern) {
vector<string> r;
unordered_set<string> cache;
for (auto word : words) {
if (word.size() != pattern.size()) {
throw invalid_argument(word + " and " + pattern +
" are not the same length");
}
if (cache.end() != cache.find(word)) {
r.push_back(word);
continue;
}
if (matches(word, pattern)) {
cache.insert(word);
r.push_back(word);
}
}
return r;
}
protected:
bool matches(const string &word, const string &pattern) {
unordered_map<char, char> p;
unordered_map<char, char> q;
// cout << "checking word '" << word << "' against pattern '" << pattern <<
// "'" << endl;
for (size_t i = 0; i < word.size(); i++) {
auto &a = word[i];
auto &b = pattern[i];
// cout << "comparing " << a << " and " << b << endl;
auto it = p.find(a);
if (p.end() == it) {
auto it2 = q.find(b);
if (q.end() == it2) {
// cout << "adding " << a << " -> " << b << endl;
p[a] = b;
q[b] = a;
} else {
// cout << it2->first << " -> " << b << " already!!! returning
// false.." << endl;
return false;
}
} else {
if (it->second != b) {
// cout << a << " -> " << it->second << " not " << b << "!!!
// returning false.." << endl;
return false;
}
}
}
// cout << "returning true" << endl;
return true;
}
};