Lexicographically next string | Python 3 program to find lexicographically next string ; If string is empty . ; Find first character from right which is not z . ; If all characters are ' z ' , append an ' a ' at the end . ; If there are some non - z characters ; Driver code
def nextWord ( s ) : NEW_LINE INDENT if ( s == " ▁ " ) : NEW_LINE INDENT return " a " NEW_LINE DEDENT i = len ( s ) - 1 NEW_LINE while ( s [ i ] == ' z ' and i >= 0 ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT if ( i == - 1 ) : NEW_LINE INDENT s = s + ' a ' NEW_LINE DEDENT else : NEW_LINE INDENT s = s . replace ( s [ i ] , chr ( ord ( s [ i ] ) + 1 ) , 1 ) NEW_LINE DEDENT return s NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " samez " NEW_LINE print ( nextWord ( str ) ) NEW_LINE DEDENT