Encrypt the string – 2

28 Jul, 2021
Given a string S consisting of N, lower case English alphabet, it is also given that a string is encrypted by first replacing every substring of the string consisting of the same character with the concatenation of that character and the hexadecimal representation of the size of the substring and then revering the whole string, the task is to find the encrypted string. 
Note: All Hexadecimal letters should be converted to Lowercase letters.
Examples:
Input: S = “aaaaaaaaaaa”Output: ba  Explanation:
First convert the given string to “a11” i.e. write, character along with its frequency.Then, change “a11” to “ab” because 11 is b in hexadecimal.Then, finally reverse the string i.e “ba”.
First convert the given string to “a11” i.e. write, character along with its frequency.
Then, change “a11” to “ab” because 11 is b in hexadecimal.
Then, finally reverse the string i.e “ba”.
Input: S = “abc”Output: 1c1b1a
Approach: The problem can be solved by iterating over the characters of the string S. Follow the steps below to solve this problem:
Initialize an empty string say, ans to store the answer.
Iterate over the characters of the string S, using the variable i, and perform the following steps:Find the count of a substring with the same character, S[i], starting from index i and store it in a variable, say, count.Now convert the count to hexadecimal representation, and append the character S[i] along with its frequencies hexadecimal representation.
Find the count of a substring with the same character, S[i], starting from index i and store it in a variable, say, count.
Now convert the count to hexadecimal representation, and append the character S[i] along with its frequencies hexadecimal representation.
Finally, reverse the string ans and then print it.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to convert Decimal to Hexstring convertToHex(int num){     string temp = "";    while (num != 0) {        int rem = num % 16;        char c;        if (rem < 10) {            c = rem + 48;        }        else {            c = rem + 87;        }        temp += c;        num = num / 16;    }     return temp;} // Function to encrypt the stringstring encryptString(string S, int N){     string ans = "";     // Iterate the characters    // of the string    for (int i = 0; i < N; i++) {         char ch = S[i];        int count = 0;        string hex;         // Iterate until S[i] is equal to ch        while (i < N && S[i] == ch) {             // Update count and i            count++;            i++;        }         // Decrement i by 1        i--;         // Convert count to hexadecimal        // representation        hex = convertToHex(count);         // Append the character        ans += ch;         // Append the characters frequency        // in hexadecimal representation        ans += hex;    }     // Reverse the obtained answer    reverse(ans.begin(), ans.end());     // Return required answer    return ans;} // Driver Codeint main(){     // Given Input    string S = "abc";    int N = S.size();     // Function Call    cout << encryptString(S, N);     return 0;}
// Java program for above approachimport java.awt.*;import java.util.*;class GFG{     // Function to convert Decimal to Hex    static String convertToHex(int num)    {         StringBuilder temp = new StringBuilder();        while (num != 0) {            int rem = num % 16;            char c;            if (rem < 10) {                c = (char) (rem + 48);            }            else {                c = (char) (rem + 87);            }            temp.append(c);            num = num / 16;        }         return temp.toString();    }     // Function to encrypt the string    static String encryptString(String S, int N)    {         StringBuilder ans = new StringBuilder();         // Iterate the characters        // of the string        for (int i = 0; i < N; i++) {             char ch = S.charAt(i);            int count = 0;            String hex;             // Iterate until S[i] is equal to ch            while (i < N && S.charAt(i) == ch) {                 // Update count and i                count++;                i++;            }             // Decrement i by 1            i--;             // Convert count to hexadecimal            // representation            hex = convertToHex(count);             // Append the character            ans.append(ch);             // Append the characters frequency            // in hexadecimal representation            ans.append(hex);        }         // Reverse the obtained answer        ans.reverse();         // Return required answer        return ans.toString();    }         // Driver Code    public static void main(String[] args)    {               // Given Input        String S = "abc";        int N = S.length();         // Function Call        System.out.println(encryptString(S, N));    }} // This code is contributed by hritikrommie.
# Python3 program for the above approach # Function to convert Decimal to Hexdef convertToHex(num):     temp = ""    while (num != 0):        rem = num % 16        c = 0                 if (rem < 10):            c = rem + 48        else:            c = rem + 87                     temp += chr(c)        num = num // 16     return temp # Function to encrypt the stringdef encryptString(S, N):     ans = ""     # Iterate the characters    # of the string    for i in range(N):        ch = S[i]        count = 0         # Iterate until S[i] is equal to ch        while (i < N and S[i] == ch):             # Update count and i            count += 1            i += 1         # Decrement i by 1        i -= 1         # Convert count to hexadecimal        # representation        hex = convertToHex(count)         # Append the character        ans += ch         # Append the characters frequency        # in hexadecimal representation        ans += hex     # Reverse the obtained answer    ans = ans[::-1]         # Return required answer    return ans # Driver Codeif __name__ == '__main__':         # Given Input    S = "abc"    N = len(S)     # Function Call    print(encryptString(S, N)) # This code is contributed by mohit kumar 29
// C# program for above approachusing System;class GFG{         // Function to convert Decimal to Hex    static string convertToHex(int num)    {          string temp = "";        while (num != 0) {            int rem = num % 16;            char c;            if (rem < 10) {                c = (char) (rem + 48);            }            else {                c = (char) (rem + 87);            }            temp = temp + c;            num = num / 16;        }          return temp;    }         // Function to encrypt the string    static string encryptString(string S, int N)    {          string ans = "";          // Iterate the characters        // of the string        for (int i = 0; i < N; i++) {              char ch = S[i];            int count = 0;            string hex;              // Iterate until S[i] is equal to ch            while (i < N && S[i] == ch) {                  // Update count and i                count++;                i++;            }              // Decrement i by 1            i--;              // Convert count to hexadecimal            // representation            hex = convertToHex(count);              // Append the character            ans = ans + ch;              // Append the characters frequency            // in hexadecimal representation            ans = ans + hex;        }          // Reverse the obtained answer        char[] Ans = ans.ToCharArray();        Array.Reverse(Ans);        ans = new string(Ans);          // Return required answer        return ans;    }       static void Main ()  {    // Given Input    string S = "abc";    int N = S.Length;     // Function Call    Console.WriteLine(encryptString(S, N));  }} // This code is contributed by suresh07.
<script> // JavaScript program for the above approach  // Function to convert Decimal to Hexfunction convertToHex(num) {     let temp = "";    while (num != 0) {        let rem = num % 16;        let c = 0;        if (rem < 10) {            c = rem + 48;        }        else {            c = rem + 87;        }        temp += String.fromCharCode(c);        num = Math.floor(num / 16);    }     return temp;} // Function to encrypt the stringfunction encryptString(S, N) {     let ans = "";     // Iterate the characters    // of the string    for (let i = 0; i < N; i++) {         let ch = S[i];        let count = 0;        let hex;         // Iterate until S[i] is equal to ch        while (i < N && S[i] == ch) {             // Update count and i            count++;            i++;        }         // Decrement i by 1        i--;         // Convert count to hexadecimal        // representation        hex = convertToHex(count);         // Append the character        ans += ch;         // Append the characters frequency        // in hexadecimal representation        ans += hex;    }     // Reverse the obtained answer    ans = ans.split('').reverse().join("");     // Return required answer    return ans;} // Driver Code  // Given Inputlet S = "abc";let N = S.length; // Function Calldocument.write(encryptString(S, N)); </script>
1c1b1a
 
Time Complexity: O(N)Auxiliary Space: O(N)
 
mohit kumar 29
_saurabh_jaiswal
hritikrommie
suresh07
Mathematical
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms
Write a program to reverse an array or string
Reverse a string in Java
Different Methods to Reverse a String in C++
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack