Repeat substrings of the given String required number of times

Given a string str, the task is to repeat every substring of the string X number of times where X is the number composed of the consecutive digits present just after the substring in the original string. For example, if str = “g1e2ks1” then the resultant string will be “geeks”.

Examples:

Input: str = “2a10bd3”
Output: aaaaaaaaaabdbdbd
First digit “2” is unnecessary as there is no valid substring before it.
“a” will be repeated 10 times and then “bd” will be repeated thrice.

Input: str = “g1ee1ks1for1g1e2ks1”
Output: geeksforgeeks

Approach: Find the first valid substring i.e. the substring which doesn’t contain any digit then parse the integer present just after the found substring using parseInt() and then repeat the found substring the required number of times. Repeat these steps for all valid substrings and then print the resultant string.

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
class GFG {
  
    // Function that returns true if the
    // passed character is a digit
    static boolean isDigit(char ch)
    {
        if (ch >= '0' && ch <= '9')
            return true;
        return false;
    }
  
    // Function to return the next index
    // of a non-digit character in the string
    // starting at the index i (returns -1 if
    // no such index is found)
    static int nextNonDigit(String str, int i)
    {
  
        // If the character at index i is a digit
        // then skip to the next character
        while (i < str.length()
               && isDigit(str.charAt(i))) {
            i++;
        }
  
        // If no such index was found
        if (i >= str.length())
            return -1;
        return i;
    }
  
    // Function to append str the given number
    // of times to the StringBuilder
    static void appendRepeated(StringBuilder sb,
                               String str, int times)
    {
        for (int i = 0; i < times; i++)
            sb.append(str);
    }
  
    // Function to return the string after
    // performing the given operations
    static String findString(String str, int n)
    {
  
        // To build the resultant string
        StringBuilder sb = new StringBuilder("");
  
        // Index of the first non-digit
        // character in the string
        int startStr = nextNonDigit(str, 0);
  
        // While there are substrings that
        // do not consist of digits
        while (startStr != -1) {
  
            // Find the ending of the substring
            int endStr = startStr;
            while ((endStr + 1) < n
                   && !isDigit(str.charAt(endStr + 1))) {
                endStr++;
            }
  
            // Starting index of the number
            int startNum = endStr + 1;
  
            // If no digit appears after
            // the current substring
            if (startNum == -1)
                break;
  
            // Find the index at which the
            // current number ends
            int endNum = startNum;
            while ((endNum + 1) < n
                   && isDigit(str.charAt(endNum + 1))) {
                endNum++;
            }
  
            // Parse the number from the substring
            int num = Integer.parseInt(str.substring(startNum,
                                                     endNum + 1));
  
            // Repeat the current substring required number of times
            appendRepeated(sb, str.substring(startStr,
                                             endStr + 1), num);
  
            // Find the next non-digit character index
            startStr = nextNonDigit(str, endStr + 1);
        }
  
        // Return the resultant string
        return sb.toString();
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String str = "g1ee1ks1for1g1e2ks1";
        int n = str.length();
        System.out.println(findString(str, n));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach
  
# Function that returns true if the
# passed character is a digit
def isDigit(ch):
    if ch >= '0' and ch <= '9':
        return True
    return False
  
# Function to return the next index
# of a non-digit character in the string
# starting at the index i (returns -1 if
# no such index is found)
def nextNonDigit(string, i):
  
    # If the character at index i is a digit
    # then skip to the next character
    while i < len(string) and isDigit(string[i]):
        i += 1
  
    # If no such index was found
    if i >= len(string):
        return -1
    return i
  
# Function to append str the given number
# of times to the StringBuilder
def appendRepeated(sb, string, times):
    for i in range(times):
        sb.append(string)
  
# Function to return the string after
# performing the given operations
def findString(string, n):
  
    # To build the resultant string
    sb = list()
  
    # Index of the first non-digit
    # character in the string
    startStr = nextNonDigit(string, 0)
  
    # While there are substrings that
    # do not consist of digits
    while startStr != -1:
  
        # Find the ending of the substring
        endStr = startStr
  
        while (endStr + 1 < n and not 
               isDigit(string[endStr + 1])):
            endStr += 1
  
        # Starting index of the number
        startNum = endStr + 1
  
        # If no digit appears 
        # after the current substring
        if startNum == -1:
            break
  
        # Find the index at which the
        # current number ends
        endNum = startNum
  
        while (endNum + 1 < n and
               isDigit(string[endNum + 1])):
            endNum += 1
  
        # Parse the number from the substring
        num = int(string[startNum:endNum + 1])
  
        # Repeat the current substring
        # required number of times
        appendRepeated(sb, string[startStr:endStr + 1], num)
  
        # Find the next non-digit character index
        startStr = nextNonDigit(string, endStr + 1)
  
    # Return the resultant string
    sb = ''.join(sb)
    return sb
  
# Driver code
if __name__ == "__main__":
    string = "g1ee1ks1for1g1e2ks1"
    n = len(string)
    print(findString(string, n))
  
# This code is contributed by
# sanjeev2552

chevron_right


Output:

geeksforgeeks


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.



Improved By : sanjeev2552



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.