加密字串


加密是一種使用某些技術或特定步驟來更改資料的技術,從而將其轉換為其他資訊,或者無法直接從中獲取先前資訊。對於加密,我們必須遵循特定步驟,這些步驟對於特定型別的加密是固定的。

在這個問題中,我們將得到一個字串,並且必須按照給定的步驟對其進行加密。

  • 首先,我們必須獲取所有包含相同字元的子字串,並將其替換為單個字元,後跟子字串的長度。

  • 現在,將長度更改為十六進位制值,並且十六進位制值的所有字元都必須更改為小寫。

  • 最後,反轉整個字串。

示例

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)。

更新於: 2023年7月26日

1K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.