Substitution Cipher
Problem statement
You and your friends share a key string, and you use it to build a substitution cipher.
Read key from left to right and keep each letter the first time you see it. A capital letter and its small form count as the same letter, and characters that are not letters are skipped. This gives all 26 letters in a fixed order. That order is the cipher alphabet.
Line the cipher alphabet up with the normal alphabet: a maps to the first cipher letter, b maps to the second, and so on up to z.
Return message encrypted with this mapping:
- Replace each letter with the letter it maps to. A capital letter gives a capital letter, and a small letter gives a small letter.
- Leave every other character, such as spaces, digits and punctuation, unchanged.
Function
encrypt(message: String, key: String) → StringExamples
Example 1
message = "It was all a dream."key = "The quick onyx goblin, Grabbing his sword ==}-------- jumps over the 1st lazy dwarf!"return = "Od ptw txx t qsutg."The key gives the cipher alphabet THEQUICKONYXGBLRASWDJMPVZF, so A becomes T, D becomes Q, and I becomes O. Capital I stays capital, small letters stay small, and the spaces and the period do not change.
Example 2
message = "Would you kindly?"key = "The quick onyx goblin, Grabbing his sword ==}-------- jumps over the 1st lazy dwarf!"return = "Pljxq zlj yobqxz?"Same key as Example 1. W becomes P, o becomes l, u becomes j, and the question mark stays as it is.
Example 3
message = "Meet at 10:30, Gate B!"key = "Five quick zebras jumped; two lynx, hog, and a cow watch?"return = "Sqqo fo 10:30, Cfoq I!"Reading the key's letters in order and skipping repeats gives FIVEQUCKZBRASJMPDTWOLYNXHG. So M becomes S, e becomes q, t becomes o, a becomes f, G becomes C, and B becomes I. The digits, the colon, the comma, the spaces and the exclamation mark stay as they are.
Constraints
1 <= message.length <= 10^426 <= key.length <= 10^4messageandkeycontain only printable ASCII characters (codes 32 to 126).keycontains every letter fromatozat least once, as a capital or a small letter.