String encryption Solution | CodeChef [Easy]

Problem

A simple string contains a large repetition of letters within it. This problem is related to string handling and manipulation. So the original string which is sent to Cybertron is encrypted in the new string which comprises the letters followed by each time it has occurred in the original string. Eg- original message is- abcdabf. Then the encrypted string is- a2b2c1d1f1

CodeChef Problem Link

Input

The input consists of a single line string without any space or numeric or special characters.

Output

It will consist of in the encrypted string which comprises the letters followed by each time it has occurred in the original string in order.

Sample Input
information
Sample Output
i2n2f1o2r1m1a1t1
Solution

Approach
Use a map (array) to store the count of each alphabet (a-z) in the string. After that iterate over the string and print each character with its count from the map in the same order as they exist in the original string.

Code Implementation

//
//  main.cpp
//  String encryption
//
//  Created by Himanshu on 16/04/22.
//

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str;
    int charMap[27] = {0};
    
    cin>>str;
    int n = (int) str.size();
    
    for (int i=0; i<n; i++) {
        charMap[str[i] - 'a']++;
    }
    
    for (int i=0; i<n; i++) {
        if (charMap[str[i] - 'a'] != 0) {
            cout<<str[i];
            cout<<charMap[str[i] - 'a'];
            charMap[str[i] - 'a'] = 0;
        }
    }

    return 0;
}

Time Complexity: O(n), where n is the length of the input string

Leave a Reply

Your email address will not be published. Required fields are marked *