Caesar's Cipher is a very famous encryption technique used in cryptography. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a shift of 3, D would be replaced by G, E would become H, X would become A, and so on.
Encryption of a letter X by a shift K can be described mathematically as % .
Given a plaintext and its corresponding ciphertext, output the minimum non-negative value of shift that was used to encrypt the plaintext or else output -1 if it is not possible to obtain the given ciphertext from the given plaintext using Caesar's Cipher technique.
Example:
Input: A = "ABC", B = "DEF"
Output: 3
Approach
C++
#include <bits/stdc++.h>using namespace std;int caesarCipher(string A, string B){unordered_map<char, int> ump;for (int i = 0; i < 26; i++)ump['A' + i] = i;if (A == B)return 0;else{int k = 0;for (int j = 0; j <= 26; j++){if ((ump[A[0]] + j) % 26 == ump[B[0]]){k = j;break;}}int flag = 0;for (int i = 1; i < B.size(); i++){if ((ump[A[i]] + k) % 26 != ump[B[i]]){flag = 1;break;}}if (flag)return -1;elsereturn k;}}int main(){string A = "ABC", B = "DEF";cout << caesarCipher(A, B) << "\n";return 0;}
No comments:
Post a Comment