LeetCode 2227. Encrypt and Decrypt Strings

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
class Encrypter {
private:
unordered_map<char, string> k2v;
unordered_map<string, int> encrypted_dict;
public:
Encrypter(vector<char>& keys, vector<string>& values, vector<string>& dictionary) {
for (int i = 0; i < keys.size(); ++i)
k2v[keys[i]] = values[i];
unordered_map<string, string> dict;
for (string &s : dictionary) {
if (dict.count(s)) {
++encrypted_dict[dict[s]];
} else {
string encryptedStr = "";
for (char c : s) encryptedStr += k2v[c];
++encrypted_dict[encryptedStr];
dict[s] = encryptedStr;
}
}
}

string encrypt(string word1) {
string ans;
for (char &c : word1) ans += k2v[c];
return ans;
}

int decrypt(string word2) {
return encrypted_dict[word2];
}
};

/**
* Your Encrypter object will be instantiated and called as such:
* Encrypter* obj = new Encrypter(keys, values, dictionary);
* string param_1 = obj->encrypt(word1);
* int param_2 = obj->decrypt(word2);
*/