给定两个包含字母数字字符和数字N 的字符串str1和str2 。的任务是形成含有与N个字符一个凯撒加密和在奇数索引与N个字符一个凯撒加密字符串STR2字符串STR1一个新的加密的字符串。
例子:
Input: str1 = “GeekforGeeks”, str2 = “Geeks123”, N = 4
Output: KiiojsvKiiowKeikw163
Explanation:
Caesar Text for string str1 with a shift of 4 is “KiiojsvKiiow”
Caesar Text for string str2 with a shift of 4 at all even indexes is “Keikw163”
Resultant string is “KiiojsvKiiow” + “Keikw163” = “KiiojsvKiiowKeikw163”
Input: str1 = “ABcdE23”, str2 = “efda2w”, N = 9
Output: JKlmN12nfma1w
Explanation:
Caesar Text for string str1 with a shift of 9 is “JKlmN12”
Caesar Text for string str2 with a shift of 9 at all even indexes is “nfma1w”
Resultant string is “JKlmN12” + “nfma1w” = “JKlmN12nfma1w”
方法:
本题是凯撒密码在密码学中的一个应用。以下是步骤:
这个想法是遍历给定的字符串str1和str2并根据以下 3 种情况将str1 的每个索引处和str2的偶数索引处的所有字符转换为N的移位:
- 情况 1:如果字符位于 ‘A’ 和 ‘Z’ 之间,则当前字符加密为:
new_character = ( (current_character - 65 + N) % 26 ) + 65;
- 情况 2:如果字符位于 ‘a’ 和 ‘z’ 之间,则当前字符加密为:
new_character = ( (current_character - 97 + N) % 26 ) + 97;
- 情况 3:如果字符位于 ‘A’ 和 ‘Z’ 之间,则当前字符加密为:
new_character = ( (current_character - 48 + N) % 10 ) + 48;
下面是上述方法的实现:
// C++ implementation of the above
// approach
#include
using namespace std;
void printCaesarText(string str1,
string str2, int N)
{
// Traverse the string str1
for (int i = 0; str1[i]; i++) {
// Current character
char ch = str1[i];
// Case 1:
if (ch >= 'A' && ch <= 'Z') {
str1[i] = (ch - 65 + N) % 26 + 65;
}
// Case 2:
else if (ch >= 'a' && ch <= 'z') {
str1[i] = (ch - 97 + N) % 26 + 97;
}
// Case 3:
else if (ch >= '0' && ch <= '9') {
str1[i] = (ch - 48 + N) % 10 + 48;
}
}
for (int i = 0; str2[i]; i++) {
// If current index is odd, then
// do nothing
if (i & 1)
continue;
// Current character
char ch = str2[i];
// Case 1:
if (ch >= 'A' && ch <= 'Z') {
str2[i] = (ch - 65 + N) % 26 + 65;
}
// Case 2:
else if (ch >= 'a' && ch <= 'z') {
str2[i] = (ch - 97 + N) % 26 + 97;
}
// Case 3:
else if (ch >= '0' && ch <= '9') {
str2[i] = (ch - 48 + N) % 10 + 48;
}
}
// Print the concatenated strings
// str1 + str2
cout << str1 + str2;
}
// Driver Code
int main()
{
string str1 = "GeekforGeeks";
string str2 = "Geeks123";
int N = 4;
printCaesarText(str1, str2, N);
return 0;
}
KiiojsvKiiowKeikw163
时间复杂度: O(N + M),其中 N 和 M 是两个给定字符串的长度。
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live