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