#2227

Encrypt and Decrypt Strings

master · 1775 · lc hard +32 · 38.1% accepted · 351 likes · top 17%

Description

You are given a character array keys of unique characters, a string array values where each string has length 2, and a string array dictionary of permitted plaintext strings. Implement a data structure for encryption and decryption.

Encryption:

- For each character c in the input, find index i where keys[i] == c.

- Replace c with values[i].

If any character is missing from keys, return "".

Decryption:

- For each length-2 substring s at an even index, find any i where values[i] == s. Multiple decodings may exist.

- Replace s with keys[i].

Implement the Encrypter class:

- Encrypter(char[] keys, String[] values, String[] dictionary) Initializes the object.

- String encrypt(String word1) Encrypts word1 and returns the ciphertext.

- int decrypt(String word2) Returns how many strings in dictionary encrypt to word2.

Example 1:

Input
["Encrypter", "encrypt", "decrypt"]
[[['a', 'b', 'c', 'd'], ["ei", "zf", "ei", "am"], ["abcd", "acbd", "adbc", "badc", "dacb", "cadb", "cbda", "abad"]], ["abcd"], ["eizfeiam"]]
Output
[null, "eizfeiam", 2]

Example 2:

Explanation
Encrypter encrypter = new Encrypter([['a', 'b', 'c', 'd'], ["ei", "zf", "ei", "am"], ["abcd", "acbd", "adbc", "badc", "dacb", "cadb", "cbda", "abad"]);
encrypter.encrypt("abcd"); // return "eizfeiam".
// 'a' maps to "ei", 'b' maps to "zf", 'c' maps to "ei", and 'd' maps to "am".
encrypter.decrypt("eizfeiam"); // return 2.
// "ei" can map to 'a' or 'c', "zf" maps to 'b', and "am" maps to 'd'.
// Thus, the possible strings after decryption are "abad", "cbad", "abcd", and "cbcd".
// 2 of those strings, "abad" and "abcd", appear in dictionary, so the answer is 2.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16