假设我们有一个编码的字符串,其中子字符串的重复表示为子字符串,然后是子字符串的计数。因此,如果字符串类似于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