Lexicographically first alternate vowel and consonant string | Python3 implementation of lexicographically first alternate vowel and consonant string ; ' ch ' is vowel or not ; create alternate vowel and consonant string str1 [ 0. . . l1 - 1 ] and str2 [ start ... l2 - 1 ] ; first adding character of vowel / consonant then adding character of consonant / vowel ; function to find the required lexicographically first alternate vowel and consonant string ; hash table to store frequencies of each character in ' str ' char_freq = [ 0 ] * SIZE initialize all elements of char_freq [ ] to 0 ; count vowels ; count consonants ; update frequency of ' ch ' in char_freq [ ] ; no such string can be formed ; form the vowel string ' vstr ' and consonant string ' cstr ' which contains characters in lexicographical order ; remove first character of vowel string then create alternate string with cstr [ 0. . . nc - 1 ] and vstr [ 1. . . nv - 1 ] ; remove first character of consonant string then create alternate string with vstr [ 0. . . nv - 1 ] and cstr [ 1. . . nc - 1 ] ; if both vowel and consonant strings are of equal length start creating string with consonant ; start creating string with vowel ; Driver Code
SIZE = 26 NEW_LINE def isVowel ( ch ) : NEW_LINE INDENT if ( ch == ' a ' or ch == ' e ' or ch == ' i ' or ch == ' o ' or ch == ' u ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def createAltStr ( str1 , str2 , start , l ) : NEW_LINE INDENT finalStr = " " NEW_LINE i = 0 NEW_LINE j = start NEW_LINE while j < l : NEW_LINE INDENT finalStr += str1 [ i ] + str2 [ j ] NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE DEDENT return finalStr NEW_LINE DEDENT def findAltStr ( string ) : NEW_LINE INDENT nv = 0 NEW_LINE nc = 0 NEW_LINE vstr = " " NEW_LINE cstr = " " NEW_LINE l = len ( string ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT ch = string [ i ] NEW_LINE if isVowel ( ch ) : NEW_LINE INDENT nv += 1 NEW_LINE DEDENT else : NEW_LINE INDENT nc += 1 NEW_LINE DEDENT char_freq [ ord ( ch ) - 97 ] += 1 NEW_LINE DEDENT if abs ( nv - nc ) >= 2 : NEW_LINE INDENT return " no ▁ such ▁ string " NEW_LINE DEDENT for i in range ( SIZE ) : NEW_LINE INDENT ch = chr ( i + 97 ) NEW_LINE for j in range ( 1 , char_freq [ i ] + 1 ) : NEW_LINE INDENT if isVowel ( ch ) : NEW_LINE INDENT vstr += ch NEW_LINE DEDENT else : NEW_LINE INDENT cstr += ch NEW_LINE DEDENT DEDENT DEDENT if nv > nc : NEW_LINE INDENT return vstr [ 0 ] + createAltStr ( cstr , vstr , 1 , nv ) NEW_LINE DEDENT if nc > nv : NEW_LINE INDENT return cstr [ 0 ] + createAltStr ( vstr , cstr , 1 , nc ) NEW_LINE DEDENT if cstr [ 0 ] < vstr [ 0 ] : NEW_LINE INDENT return createAltStr ( cstr , vstr , 0 , nv ) NEW_LINE DEDENT return createAltStr ( vstr , cstr , 0 , nc ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " aeroplane " NEW_LINE print ( findAltStr ( string ) ) NEW_LINE DEDENT