如何解碼使用給定演算法編碼的字串?
介紹
編碼是指將文字轉換為某種表示形式,解碼是將編碼文字轉換為其原始形式的過程。編碼和解碼是將資訊從一種形式轉換為另一種形式的兩種相互關聯的技術。在本教程中,我們實現了一種方法來解碼使用給定演算法編碼的字串,該演算法使用某種演算法編碼的編碼字串來查詢解碼後的字串。
字串使用以下概念進行編碼:
例如
string = India Encoded string = dniIa
在字串“India”中,中間字元是'd',將其儲存為編碼字串。
Encoded string = d
從字串中刪除'd'。剩餘的字串是'Inia'。
透過這種方式,我們使用解碼演算法對字串進行編碼並將其解碼為原始形式。
演示
Input = Encoded string = dniIa Output = Decoded string is "India"
解釋
編碼後的字串是“dnila”。根據解碼演算法,從編碼字串的第一個字元'd'開始解碼。將其儲存為解碼後的字串。
Decoded string = d Encoded string = nila
取字元'n'並將其儲存到解碼字串字元的左側。
Decoded string = nd Encoded string = ila
取字元'i'並將其儲存到解碼字串字元的右側。
Decoded string = ndi Encoded string = la
取字元'l'並將其儲存到解碼字串字元的左側。
Decoded string = lndi Encoded string = a
取字元'a'並將其儲存到解碼字串字元的右側。
Decoded string = India
語法
length() − 這是一個字串類庫函式,定義在<string>標頭檔案中。它以位元組為單位返回字串的長度。
string_name.length();
演算法
獲取使用列出的編碼演算法編碼的編碼字串。
使用'for'迴圈迭代編碼字串。
使用if-else條件使用解碼演算法解碼字串。
列印解碼後的字串。
示例
在C++中實現一種方法來查詢使用列出的演算法編碼的解碼字串。使用if-else條件和迴圈來查詢解碼後的字串。
#include <bits/stdc++.h>
using namespace std;
// user-defined function for decoding the input string
void decodeString(string encodedString, int stringLength) {
// variable for storing the characters of the decoded string
char ch[stringLength] = "";
int bet, p = 1, x;
if (stringLength % 2 == 1) // finding the middle character
bet = stringLength / 2;
else
bet = stringLength / 2 - 1;
ch[bet] = encodedString[0]; // storing the value of the middle character
if (stringLength % 2 == 0)
ch[bet + 1] = encodedString[1];
// x variable denotes the total characters stored in the decoded string
if (stringLength & 1)
x = 1;
else
x = 2;
//Loop to iterate the string
for (int a = x; a < stringLength; a += 2) {
ch[bet - p] = encodedString[a];
if (stringLength % 2 == 1) // When the length of the string is not even
ch[bet + p] = encodedString[a + 1];
else // When the string length is even
ch[bet + p + 1] = encodedString[a + 1];
p++; }
// loop to print each character of the decoded string
for (int a = 0; a < stringLength; a++)
cout << ch[a];}
//code controller
int main() {
string encodedString = "armgmoirnPg"; //encoded string as an input
int stringLength = encodedString.length();
//calling function to decode the string
decodeString(encodedString, stringLength);
return 0;}
Programming
結論
我們已經完成了本教程。在本教程中,我們實現了一種C++方法來解碼編碼的字串。解碼和編碼是使用某種演算法將資訊從一種形式轉換為另一種形式的技術。它廣泛應用於資料傳輸、資料壓縮、密碼學等等。
開發了一種編碼演算法並用示例進行了說明。開發了一種解碼演算法,用於查詢使用所述演算法編碼的原始字串。使用解碼和編碼演算法以及條件語句和迴圈實現了該方法。
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP