Decode the Message

Decode the Message

You are given the strings key and message, which represent a cipher key and a secret message, respectively. The steps to decode message are as follows:

  1. Use the first appearance of all 26 lowercase English letters in key as the order of the substitution table.

  2. Align the substitution table with the regular English alphabet.

  3. Each letter in message is then substituted using the table.

  4. Spaces ' ' are transformed to themselves.

  • For example, given key = "happy boy" (actual key would have at least one instance of each letter in the alphabet), we have the partial substitution table of ('h' -> 'a', 'a' -> 'b', 'p' -> 'c', 'y' -> 'd', 'b' -> 'e', 'o' -> 'f').

Return the decoded message.

LeetCode Problem - 2325

import java.util.*;

class Solution {
    // Method to decode a message using a given key
    public String decodeMessage(String key, String message) {
        // Removing spaces from the key
        String keyWithoutSpace = key.replaceAll("\\s+","");
        // Creating a map to store the key-value pairs
        Map<Character, Character> hm = new HashMap<>();

        // Assigning values to characters in the key
        char value = 'a';
        for (int i = 0; i < keyWithoutSpace.length(); i++) {
            if (!hm.containsKey(keyWithoutSpace.charAt(i))) {
                hm.put(keyWithoutSpace.charAt(i), value);
                value++;
            }
        }

        // Splitting the message into words
        String[] msgArr = message.split(" ");
        List<String> list = new ArrayList<>();

        // Decoding each word in the message
        for (String string : msgArr) {
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < string.length(); j++) {
                sb.append(hm.get(string.charAt(j)));
            }
            list.add(sb.toString());
        }

        // Constructing the decoded message
        StringBuilder ans = new StringBuilder(String.join(" ", list));
        // Adding necessary spaces to match the length of the original message
        if (ans.length() != message.length()) {
            int diff = message.length() - ans.length();
            ans.append(" ".repeat(Math.max(0, diff)));
        }

        // Returning the decoded message
        return ans.toString();
    }
}

Did you find this article valuable?

Support Gulshan Kumar by becoming a sponsor. Any amount is appreciated!