Leetcode 2325. Decode the Message
You are given a string key
and a string message
which has been encoded using a substitution cipher based on the key. Find the original decoded message.
To decode the message:
key
(ignoring duplicates and non-letter characters) to the 26 lowercase English letters in order. For example, if the key is “the quick brown fox jumps over the lazy dog”, the mapping would be: {'t': 'a', 'h': 'b', 'e': 'c', 'q': 'd', 'u': 'e', 'i': 'f', ...}
.message
by replacing each letter in message
with its corresponding letter in the mapping. Any character in the message
that is not a letter should remain unchanged.message
that aren’t present in key
?
message
that are not letters should remain unchanged in the output.key
and message
guaranteed to be in lowercase?
key
and message
are given in lowercase.key
is shorter than the English alphabet or doesn’t contain all 26 letters?
key
will contain at least all the letters required to decode the message properly.key
and build a mapping to the 26 lowercase English letters in order. Ensure that duplicates are ignored.message
with its corresponding mapped character, leaving non-letter characters unchanged.message
, return the decoded version.#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <string>
std::string decodeMessage(const std::string& key, const std::string& message) {
std::unordered_map<char, char> mapping;
std::unordered_set<char> seen;
char currentChar = 'a';
// Create the mapping from the key
for (char c : key) {
if (c >= 'a' && c <= 'z') {
if (seen.find(c) == seen.end()) {
mapping[c] = currentChar;
currentChar++;
seen.insert(c);
}
}
}
// Decode the message
std::string decodedMessage;
decodedMessage.reserve(message.size());
for (char c : message) {
if (c >= 'a' && c <= 'z') {
decodedMessage += mapping[c];
} else {
decodedMessage += c;
}
}
return decodedMessage;
}
int main() {
std::string key = "the quick brown fox jumps over the lazy dog";
std::string message = "vkbs bs t suepuv";
std::string decodedMessage = decodeMessage(key, message);
std::cout << "Decoded Message: " << decodedMessage << std::endl;
return 0;
}
key
. This is because we traverse the key once.message
. This is because we traverse the message once.Overall, the time complexity is O(N + M), which is efficient for this problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?