在 C++ 中查詢解密字串的第 k 個字元
假設我們有一個經過編碼的字串,其中子串重複表現為子串後跟子串計數。因此,如果字串類似於 ab2cd2,則它表示 ababcdcd,如果 k = 4,則它將返回第 k 個字元,即此處的 b。
要解決此問題,我們最初採用空解密字串,然後透過逐個讀取子串及其頻率來解壓縮字串。然後按其頻率將當前子串附加到解密字串中。我們將重複此過程,直到字串用盡,並從解密字串中列印第 K 個字元。
示例
#include<iostream>
using namespace std;
char findKthCharacter(string str,int k) {
string decrypted = "";
string temp;
int occurrence = 0;
for (int i=0; str[i]!='\0'; ){
temp = "";
occurrence = 0;
while (str[i]>='a' && str[i]<='z'){
temp += str[i];
i++;
}
while (str[i]>='1' && str[i]<='9') {
occurrence = occurrence*10 + str[i] - '0';
i++;
}
for (int j=1; j<=occurrence; j++)
decrypted = decrypted + temp;
}
if (occurrence==0)
decrypted = decrypted + temp;
return decrypted[k-1];
}
int main() {
string str = "ab4c12ed3";
int k = 21;
cout << k << "th character in decrypted string: " << findKthCharacter(str, k);
}輸出
21th character in decrypted string: e
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP