LeetCode 2227: Encrypt and Decrypt Strings

Problem Description

Explanation

To solve this problem, we can use two maps: one for encryption (character to string mapping) and another for decryption (string to character mapping). When encrypting a string, we iterate through each character and replace it with its corresponding value from the encryption map. When decrypting a string, we iterate through each pair of characters and replace it with any key from the decryption map that matches the pair.

Time Complexity

  • Initialization: O(n), where n is the number of keys/values in the constructor.
  • Encryption: O(m), where m is the length of the input word1.
  • Decryption: O(m), where m is the length of the input word2.

Space Complexity

  • O(n) for storing the encryption and decryption maps.

Solutions

import java.util.HashMap;

class Encrypter {
    HashMap<Character, String> encryptMap;
    HashMap<String, Character> decryptMap;

    public Encrypter(char[] keys, String[] values, String[] dictionary) {
        encryptMap = new HashMap<>();
        decryptMap = new HashMap<>();

        for (int i = 0; i < keys.length; i++) {
            encryptMap.put(keys[i], values[i]);
            decryptMap.put(values[i], keys[i]);
        }
    }

    public String encrypt(String word1) {
        StringBuilder encrypted = new StringBuilder();
        for (char c : word1.toCharArray()) {
            if (encryptMap.containsKey(c)) {
                encrypted.append(encryptMap.get(c));
            } else {
                return "";
            }
        }
        return encrypted.toString();
    }

    public int decrypt(String word2) {
        int count = 1;
        for (int i = 0; i < word2.length(); i += 2) {
            String pair = word2.substring(i, i + 2);
            if (decryptMap.containsKey(pair)) {
                char decryptedChar = decryptMap.get(pair);
                count *= 2; // Double the count for every valid decryption option
            }
        }
        return count / 2; // Divide by 2 to account for doubling in the loop
    }
}

Loading editor...