![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find k’th character of decrypted string in C++
Suppose we have one encoded string, where repetitions of substrings are represented as substring followed by count of substrings. So if the string is like ab2cd2, it indicates ababcdcd, and if k = 4, then it will return kth character, that is b here.
To solve this, we initially take empty decrypted string then decompress the string by reading substring and its frequency one by one. Then append current substring in the decrypted string by its frequency. We will repeat this process till the string has exhausted, and print the Kth character from decrypted string.
Example
#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); }
Output
21th character in decrypted string: e
Advertisements