在 C++ 中查找字符串解密后的第 k 个字符的程序
在本文中,我们将讨论一个用于查找字符串解密后的第 k 个字符的程序。
为此,我们会得到一个字符串,其中包含字符和数字及整数 K。我们的任务是解密给定的字符串并找到位于第 k 个位置的字符。
示例
#include <cstdlib>
#include <iostream>
using namespace std;
//finding decrypted Kth character
char findKthChar(string s, int k) {
int len = s.length();
int i = 0;
int total_len = 0;
while (i < len) {
if (isalpha(s[i])) {
total_len++;
if (total_len == k)
return s[i];
i++;
}
else {
int n = 0;
while (i < len && !isalpha(s[i])) {
n = n * 10 + (s[i] - '0');
i++;
}
int next_total_len = total_len * n;
if (k <= next_total_len) {
int pos = k % total_len;
if (!pos) {
pos = total_len;
}
return findKthChar(s, pos);
}
else {
total_len = next_total_len;
}
}
}
return -1;
}
int main() {
string s = "ab2c3";
int k = 5;
cout << findKthChar(s, k);
return 0;
}输出
c
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP