给定两个包含字母数字字符和数字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种情况下,将N的移位将str1的每个索引和str2的偶数索引处的所有字符转换:
- 情况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现场课程》和《 Geeks现场课程美国》。