加密字符串
加密是一种使用某些技术或特定步骤来更改数据的技术,从而将其转换为其他信息,或者无法直接从中获取先前信息。对于加密,我们必须遵循特定步骤,这些步骤对于特定类型的加密是固定的。
在这个问题中,我们将得到一个字符串,并且必须按照给定的步骤对其进行加密。
首先,我们必须获取所有包含相同字符的子字符串,并将其替换为单个字符,后跟子字符串的长度。
现在,将长度更改为十六进制值,并且十六进制值的所有字符都必须更改为小写。
最后,反转整个字符串。
示例
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 时间,而对于字符串的反转,它与 N 相比要少。
以上代码的空间复杂度为 O(N),用于存储最终字符串,如果我们忽略它,则没有使用额外的空间。
注意
加密可以通过无限多种方式完成,并且只取决于如何定义加密密钥的规则。加密的主要内容是它必须每次对相同的输入产生相同的结果。
结论
在本教程中,我们实现了一个代码来根据规则加密给定的字符串,首先,我们必须获取包含相同类型元素的子字符串,并将它们替换为字符及其频率。在下一步中,我们将频率更改为十六进制数,最后反转整个字符串。以上代码的时间复杂度为 O(N)。
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP