Decode a string recursively encoded as count followed by substring | Returns decoded string for ' str ' ; Traversing the string ; If number , convert it into number and push it into integerstack . ; If closing bracket ' ] ' , pop elemment until ' [ ' opening bracket is not found in the character stack . ; Repeating the popped string ' temo ' count number of times . ; Push it in the character stack . ; If ' [ ' opening bracket , push it into character stack . ; Pop all the elmenet , make a string and return . ; Driven code
def decode ( Str ) : NEW_LINE INDENT integerstack = [ ] NEW_LINE stringstack = [ ] NEW_LINE temp = " " NEW_LINE result = " " NEW_LINE i = 0 NEW_LINE while i < len ( Str ) : NEW_LINE INDENT count = 0 NEW_LINE if ( Str [ i ] >= '0' and Str [ i ] <= '9' ) : NEW_LINE INDENT while ( Str [ i ] >= '0' and Str [ i ] <= '9' ) : NEW_LINE INDENT count = count * 10 + ord ( Str [ i ] ) - ord ( '0' ) NEW_LINE i += 1 NEW_LINE DEDENT i -= 1 NEW_LINE integerstack . append ( count ) NEW_LINE DEDENT elif ( Str [ i ] == ' ] ' ) : NEW_LINE INDENT temp = " " NEW_LINE count = 0 NEW_LINE if ( len ( integerstack ) != 0 ) : NEW_LINE INDENT count = integerstack [ - 1 ] NEW_LINE integerstack . pop ( ) NEW_LINE DEDENT while ( len ( stringstack ) != 0 and stringstack [ - 1 ] != ' [ ' ) : NEW_LINE INDENT temp = stringstack [ - 1 ] + temp NEW_LINE stringstack . pop ( ) NEW_LINE DEDENT if ( len ( stringstack ) != 0 and stringstack [ - 1 ] == ' [ ' ) : NEW_LINE INDENT stringstack . pop ( ) NEW_LINE DEDENT for j in range ( count ) : NEW_LINE INDENT result = result + temp NEW_LINE DEDENT for j in range ( len ( result ) ) : NEW_LINE INDENT stringstack . append ( result [ j ] ) NEW_LINE DEDENT result = " " NEW_LINE DEDENT elif ( Str [ i ] == ' [ ' ) : NEW_LINE INDENT if ( Str [ i - 1 ] >= '0' and Str [ i - 1 ] <= '9' ) : NEW_LINE INDENT stringstack . append ( Str [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT stringstack . append ( Str [ i ] ) NEW_LINE integerstack . append ( 1 ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT stringstack . append ( Str [ i ] ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT while len ( stringstack ) != 0 : NEW_LINE INDENT result = stringstack [ - 1 ] + result NEW_LINE stringstack . pop ( ) NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Str = "3 [ b2 [ ca ] ] " NEW_LINE print ( decode ( Str ) ) NEW_LINE DEDENT