C++ 加密字符串
加密是通过使用某些技术或特定步骤来改变数据的技术,使其变成另一种信息或无法直接从中获取到原始信息。对于加密,我们必须遵循特定的步骤,这些步骤对于特定类型的加密是固定的。
在这个问题中,我们将给出一个字符串,我们必须按照给定的步骤进行加密:
- 首先,我们必须获取包含相同字符的所有子字符串,并用一个字符和子字符串的长度替换该子字符串。
-
现在,将长度改为十六进制值,并且十六进制值的所有字符必须改为小写。
-
最后,反转整个字符串。
示例
Input 1: string str = "aabbbcccc"
Output: "4c3b2a"
解释
首先,我们将获取包含相同字符数的所有子字符串,并将它们替换为它们的字符的频率,这将给我们提供字符串“a2b3c4”。现在,我们将长度改为十六进制值,但是2、3和4在十六进制形式中具有相同的值。最后,我们将反转字符串,最终结果将为4c3b2a。
Input2: string str = "oooooooooooo"
Output: "co"
解释
首先,我们将字符串转换为频率字符串,即“o12”。现在,12的十六进制值是C,我们将其转换为小写字母c,并在字符串中替换它,然后反转字符串。
方法
从上面的示例中,我们对问题有了一个概念,现在让我们转向实现部分。
- 在实现中,首先我们将实现一个函数,将一个整数作为输入,并将字符串作为返回值。
-
这个函数将用于将给定的整数转换为十六进制值,其中一个修改是使用小写英文字母而不是大写英文字母。
-
我们将定义另一个函数,其中我们将使用for循环遍历字符串,然后对于相同字符的子字符串,我们将使用while循环,直到找到与当前字符相等的字符为止。
-
我们将计算频率,并将其转换为十六进制值,并将其添加到带有当前索引字符的字符串中。
-
最后,我们将反转字符串并将其返回以在主函数中打印。
示例
#include <bits/stdc++.h>
using namespace std;
// function to convert the integer to hexadecimal values
string convertToHexa(int val){
string res = ""; // string to store the result
while(val != 0){
int cur = val %16; // getting the mode of the current value
if(cur < 10){
res += '0' + cur;
}
else{
res += 87 + cur; // adding 87 to get the lowercase letters
}
val /= 16; // updating the current value
}
return res;
}
// function to encrypt the string
string encrypt(string str){
int len = str.length(); // getting the length of the string
int freq = 0; // variable to store the frequency
string ans = ""; // string to store the answer
// traversing over the string
for(int i=0; i<len; i++){
int j = i; // variable to keep track the substring with the same character
while(j < len && str[j] == str[i]){
j++;
}
freq = j-i;
ans += str[i];
// calling the function to get the hexadecimal value
string hexaValue = convertToHexa(freq);
ans += hexaValue;
i = j-1;
}
// reversing the string
reverse(ans.begin(), ans.end());
return ans;
}
// main function
int main(){
string str = "aaabbbbccccccccccc"; // given string
// calling the function to get the encrypted string
cout<<"The given string after the encryption is: "<<encrypt(str)<<endl;
return 0;
}
输出
The given string after the encryption is: bc4b3a
时间和空间复杂度
上述代码的时间复杂度是O(N),其中N是给定字符串的大小。我们遍历字符串的时间为N,并且字符串的反转时间相对较小。
上述代码的空间复杂度是O(N),用于存储最终字符串,如果忽略这部分,则没有额外的空间使用。
注意
加密可以通过无限种方式进行,只有规则如何定义加密密钥才是重要的。加密的主要目的是对于相同的输入,每次都必须给出相同的结果。
结论
在本教程中,我们实现了一个代码,根据规则对给定字符串进行加密。首先,我们获取包含相同类型元素的子字符串,并将它们替换为字符及其频率。然后,我们将频率转换为十六进制数并对整个字符串进行反转。上述代码的时间复杂度为O(N)。