Program to find the kth character after decrypting a string

Given a string str consisting of characters and numbers and an integer k, the task is to decrypt the string and the return the kth character in the decrypted string.

In order to decrypt the string, traverse the string character by character and if the current character is an alphabet then append it to the resultant string else if it is a numeric digit then parse the number and repeat the resultant string this parsed number of times and continue with the original string. For example, str = “ab2c3” will be decrypted as “ababcababcababc”.

Examples:

Input: str = “ab2c3”, k = 5
Output: c
Decrypted string will be “ababcababcababc” and ‘c’ is the fifth character.

Input: str = “x2y3”, k = 3
Output: y



Approach:

  • Initialize starting index i = 0 and total_len = 0.
  • Loop while i is less then the length of the input string and check if current character is an alphabet or not. If yes then increment total_len by 1 and check if total length is less then or equal to k if yes then return the string else increment i.
  • Initialize n = 0 again loop while i is less then length of input string and i is not an alphabet and parse the number and increment i and find the next_total_len = total_len * n.
    • If k < total_len then get the position of the character by initializing pos = k % total_len.
    • If position is not found then update position = total_len and finally return the character at kth position. If not found then return -1.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <cstdlib>
#include <iostream>
using namespace std;
  
// Function to print kth charecter of
// String s after decrypting it
char findKthChar(string s, int k)
{
  
    // Get the length of string
    int len = s.length();
  
    // Initialise pointer to charecter
    // of input string to zero
    int i = 0;
  
    // Total length of resultant string
    int total_len = 0;
  
    // Traverse the string from starting
    // and check if each character is
    // alphabet then increament total_len
    while (i < len) {
        if (isalpha(s[i])) {
  
            total_len++;
  
            // If total_leg equal to k then
            // return string else increment i
            if (total_len == k)
                return s[i];
  
            i++;
        }
  
        else {
  
            // Parse the number
            int n = 0;
            while (i < len && !isalpha(s[i])) {
                n = n * 10 + (s[i] - '0');
                i++;
            }
  
            // Update next_total_len
            int next_total_len = total_len * n;
  
            // Get the position of kth charecter
            if (k <= next_total_len) {
                int pos = k % total_len;
  
                // Position not found then update
                // position with total_len
                if (!pos) {
                    pos = total_len;
                }
  
                // Recursively find the kth position
                return findKthChar(s, pos);
            }
            else {
  
                // Else update total_len
                // by next_total_len
                total_len = next_total_len;
            }
        }
    }
  
    // Return -1 if charecter not found
    return -1;
}
  
// Driver code
int main()
{
    string s = "ab2c3";
    int k = 5;
  
    cout << findKthChar(s, k);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach 
import java.util.*;
class GfG 
  
// Function to print kth charecter of 
// String s after decrypting it 
static Character findKthChar(String s, int k) 
  
    // Get the length of string 
    int len = s.length(); 
  
    // Initialise pointer to charecter 
    // of input string to zero 
    int i = 0
  
    // Total length of resultant string 
    int total_len = 0
  
    // Traverse the string from starting 
    // and check if each character is 
    // alphabet then increament total_len 
    while (i < len)
    
        if (Character.isLetter(s.charAt(i)))
        
  
            total_len++; 
  
            // If total_leg equal to k then 
            // return string else increment i 
            if (total_len == k) 
                return s.charAt(i); 
  
            i++; 
        
  
        else
        
  
            // Parse the number 
            int n = 0
            while (i < len && !Character.isLetter(s.charAt(i)))
            
                n = n * 10 + (s.charAt(i) - '0'); 
                i++; 
            
  
            // Update next_total_len 
            int next_total_len = total_len * n; 
  
            // Get the position of kth charecter 
            if (k <= next_total_len)
            
                int pos = k % total_len; 
  
                // Position not found then update 
                // position with total_len 
                if (pos == 0)
                
                    pos = total_len; 
                
  
                // Recursively find the kth position 
                return findKthChar(s, pos); 
            
            else 
            
  
                // Else update total_len 
                // by next_total_len 
                total_len = next_total_len; 
            
        
    
  
    // Return -1 if charecter not found 
    return ' '
  
// Driver code 
public static void main(String[] args) 
    String s = "ab2c3"
    int k = 5
  
    System.out.println(findKthChar(s, k)); 
}
  
// This code is contributed by Prerna Saini.

chevron_right


Python3

# Python 3 implementation of the approach

# Function to print kth charecter of
# String s after decrypting it
def findKthChar(s, k):

# Get the length of string
len1 = len(s)

# Initialise pointer to charecter
# of input string to zero
i = 0

# Total length of resultant string
total_len = 0

# Traverse the string from starting
# and check if each character is
# alphabet then increament total_len
while (i < len1): if (s[i].isalpha()): total_len += 1 # If total_leg equal to k then # return string else increment i if (total_len == k): return s[i] i += 1 else: # Parse the number n = 0 while (i < len1 and s[i].isalpha() == False): n = n * 10 + (ord(s[i]) - ord('0')) i += 1 # Update next_total_len next_total_len = total_len * n # Get the position of kth charecter if (k <= next_total_len): pos = k % total_len # Position not found then update # position with total_len if (pos == 0): pos = total_len # Recursively find the kth position return findKthChar(s, pos) else: # Else update total_len # by next_total_len total_len = next_total_len # Return -1 if charecter not found return -1 # Driver code if __name__ == '__main__': s = "ab2c3" k = 5 print(findKthChar(s, k)) # This code is contributed by # Surendra_Gangwar [tabbyending]

Output:

c


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.