Find k'th character of decrypted string | Set 1 - GeeksforGeeks

16 Jul, 2021
Given an encoded string where repetitions of substrings are represented as substring followed by count of substrings. For example, if encrypted string is “ab2cd2” and k=4 , so output will be ‘b’ because decrypted string is “ababcdcd” and 4th character is ‘b’.Note: Frequency of encrypted substring can be of more than one digit. For example, in “ab12c3”, ab is repeated 12 times. No leading 0 is present in frequency of substring. Examples:  
Input: "a2b2c3", k = 5
Output: c
Decrypted string is "aabbccc"

Input : "ab4c2ed3", k = 9
Output : c
Decrypted string is "ababababccededed"

Input: "ab4c12ed3", k = 21
Output: e
Decrypted string is "ababababccccccccccccededed"
 
The idea is simple. Initially take empty decrypted string then decompress the string by reading substring and it’s frequency one by one and append current substring in decrypted string by it’s frequency. Repeat the process till the end of string and print the K’th character from decrypted string.  
C++
Java
Python3
C#
Javascript
// C++ program to find K'th character in// decrypted string#include<bits/stdc++.h>using namespace std; // Function to find K'th character in Encoded Stringchar encodedChar(string str,int k){    // expand string variable is used to    // store final string after decompressing string str    string expand = "";     string temp;  // Current substring    int freq = 0; // Count of current substring     for (int i=0; str[i]!='\0'; )    {        temp = ""; // Current substring        freq = 0; // count frequency of current substring         // read characters until you find a number        // or end of string        while (str[i]>='a' && str[i]<='z')        {            // push character in temp            temp.push_back(str[i]);            i++;        }         // read number for how many times string temp        // will be repeated in decompressed string        while (str[i]>='1' && str[i]<='9')        {            // generating frequency of temp            freq = freq*10 + str[i] - '0';            i++;        }         // now append string temp into expand        // equal to its frequency        for (int j=1; j<=freq; j++)            expand.append(temp);    }     // this condition is to handle the case    // when string str is ended with alphabets    // not with numeric value    if (freq==0)        expand.append(temp);     return expand[k-1];} // Driver program to test the stringint main(){    string str = "ab4c12ed3";    int k = 21;    cout << encodedChar(str, k) << endl;    return 0;}
// Java program to find K'th character in// decrypted stringpublic class GFG {          // Function to find K'th character in    // Encoded String    static char encodedChar(String str,int k)    {        // expand string variable is used to        // store final string after decompressing        // string str        String expand = "";              String temp = "";  // Current substring        int freq = 0; // Count of current substring              for (int i=0; i < str.length() ; )        {            temp = ""; // Current substring            freq = 0; // count frequency of current                      // substring                  // read characters until you find a number            // or end of string            while (i < str.length() && str.charAt(i)>='a'                                && str.charAt(i)<='z')            {                // push character in temp                temp += str.charAt(i);                i++;            }                  // read number for how many times string temp            // will be repeated in decompressed string            while (i < str.length() && str.charAt(i)>='1'                                && str.charAt(i)<='9')            {                // generating frequency of temp                freq = freq*10 + str.charAt(i) - '0';                i++;            }                  // now append string temp into expand            // equal to its frequency            for (int j=1; j<=freq; j++)                 expand += temp;        }              // this condition is to handle the case        // when string str is ended with alphabets        // not with numeric value        if (freq==0)            expand += temp;              return expand.charAt(k-1);    }          // Driver program to test the string    public static void main(String args[])    {        String str = "ab4c12ed3";        int k = 21;        System.out.println(encodedChar(str, k));    }}// This code is contributed by Sumit Ghosh
# Python 3 program to find K'th character# in decrypted string # Function to find K'th character# in Encoded Stringdef encodedChar(str, k):         # expand string variable is used    # to store final string after    # decompressing string str    expand = ""     # Current substring    freq = 0 # Count of current substring    i = 0    while(i < len(str)):        temp = "" # Current substring        freq = 0 # count frequency of current substring         # read characters until you find        # a number or end of string        while (i < len(str) and               ord(str[i]) >= ord('a') and               ord(str[i]) <= ord('z')):                                # push character in temp            temp += str[i]            i += 1         # read number for how many times string temp        # will be repeated in decompressed string        while (i < len(str) and               ord(str[i]) >= ord('1') and               ord(str[i]) <= ord('9')):                                # generating frequency of temp            freq = freq * 10 + ord(str[i]) - ord('0')            i += 1         # now append string temp into expand        # equal to its frequency        for j in range(1, freq + 1, 1):            expand += temp     # this condition is to handle the case    # when string str is ended with alphabets    # not with numeric value    if (freq == 0):        expand += temp     return expand[k - 1] # Driver Codeif __name__ == '__main__':    str = "ab4c12ed3"    k = 21    print(encodedChar(str, k)) # This code is contributed by# Shashank_Sharma
// C# program to find K'th// character in decrypted stringusing System; class GFG{         // Function to find K'th    // character in Encoded String    static char encodedChar(string str, int k)    {        // expand string variable is        // used to store final string        // after decompressing string str        String expand = "";             String temp = ""; // Current substring        int freq = 0; // Count of current substring             for (int i = 0; i < str.Length ; )        {            temp = ""; // Current substring            freq = 0; // count frequency of current                      // substring                 // read characters until you            // find a number or end of string            while (i < str.Length && str[i]>='a'                                  && str[i]<='z')            {                // push character in temp                temp += str[i];                i++;            }                 // read number for how many times            // string temp will be repeated            // in decompressed string            while (i < str.Length && str[i] >= '1'                                  && str[i] <= '9')            {                // generating frequency of temp                freq = freq * 10 + str[i] - '0';                i++;            }                 // now append string temp into            // expand equal to its frequency            for (int j = 1; j <= freq; j++)                expand += temp;        }             // this condition is to handle        // the case when string str is        // ended with alphabets not        // with numeric value        if (freq == 0)            expand += temp;             return expand[k - 1];    }         // Driver Code    public static void Main()    {        string str = "ab4c12ed3";        int k = 21;        Console.Write(encodedChar(str, k));    }} // This code is contributed// by ChitraNayal
<script>// Javascript program to find K'th character in// decrypted string         // Function to find K'th character in    // Encoded String    function encodedChar(str, k)    {             // expand string variable is used to        // store final string after decompressing        // string str        let expand = "";        let temp = "";  // Current substring        let freq = 0; // Count of current substring        for (let i=0; i < str.length ; )        {            temp = ""; // Current substring            freq = 0; // count frequency of current                      // substring                    // read characters until you find a number            // or end of string            while (i < str.length && str[i].charCodeAt(0)>='a'.charCodeAt(0)                                && str[i].charCodeAt(0)<='z'.charCodeAt(0))            {                // push character in temp                temp += str[i];                i++;            }                    // read number for how many times string temp            // will be repeated in decompressed string            while (i < str.length && str[i].charCodeAt(0)>='1'.charCodeAt(0)                                && str[i].charCodeAt(0)<='9'.charCodeAt(0))            {                // generating frequency of temp                freq = freq*10 + str[i].charCodeAt(0) - '0'.charCodeAt(0);                i++;            }                    // now append string temp into expand            // equal to its frequency            for (let j=1; j<=freq; j++)                 expand += temp;        }                // this condition is to handle the case        // when string str is ended with alphabets        // not with numeric value        if (freq==0)            expand += temp;                return expand[k-1];    }         // Driver program to test the string    let str = "ab4c12ed3";    let k = 21;    document.write(encodedChar(str, k));         // This code is contributed by avanitrachhadiya2155</script>
Output:  
e
 
YouTubeGeeksforGeeks502K subscribersFind k’th character of decrypted string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:26•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=OrU84a6cdGI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Exercise : The above solution builds the decoded string to find k’th character. Extend the solution to work in O(1) extra space.Find k-th character of decrypted string | Set – 2This article is contributed by Shashank Mishra ( Gullu ) and reviewed by team GeeksforGeeks. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
ukasp
Shashank_Sharma
avanitrachhadiya2155
adnanirshad158
String-Run Length Encoding
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
Different methods to reverse a string in C/C++
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Array of Strings in C++ (5 Different Ways to Create)
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Reverse words in a given string
Top 50 String Coding Problems for Interviews