Rearrange characters in a sorted string such that no pair of adjacent characters are the same | Python 3 program for the above approach ; Function to check if a string S contains pair of adjacent characters that are equal or not ; Traverse the string S ; If S [ i ] and S [ i + 1 ] are equal ; Otherwise , return false ; Function to rearrange characters of a string such that no pair of adjacent characters are the same ; Initialize 3 variables ; Iterate until k < N ; If S [ i ] is not equal to S [ j ] ; Increment i and j by 1 ; If j equals k and increment the value of K by 1 ; Else ; If S [ j ] equals S [ k ] ; Increment k by 1 ; Else ; Swap ; Increment i and j by 1 ; If j equals k ; Increment k by 1 ; Function to rearrange characters in a string so that no two adjacent characters are same ; If string is already valid ; If size of the string is 2 ; Function Call ; Reversing the string ; Function Call ; If the string is valid ; Otherwise ; Driver Code
S = " aaabc " NEW_LINE def isAdjChar ( s ) : NEW_LINE INDENT for i in range ( len ( s ) - 1 ) : NEW_LINE INDENT if ( s [ i ] == s [ i + 1 ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def rearrangeStringUtil ( N ) : NEW_LINE INDENT global S NEW_LINE S = list ( S ) NEW_LINE i = 0 NEW_LINE j = 1 NEW_LINE k = 2 NEW_LINE while ( k < N ) : NEW_LINE INDENT if ( S [ i ] != S [ j ] ) : NEW_LINE INDENT i += 1 NEW_LINE j += 1 NEW_LINE if ( j == k ) : NEW_LINE INDENT k += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( S [ j ] == S [ k ] ) : NEW_LINE INDENT k += 1 NEW_LINE DEDENT else : NEW_LINE INDENT temp = S [ k ] NEW_LINE S [ k ] = S [ j ] NEW_LINE S [ j ] = temp NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE if ( j == k ) : NEW_LINE INDENT k += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT S = ' ' . join ( S ) NEW_LINE DEDENT def rearrangeString ( N ) : NEW_LINE INDENT global S NEW_LINE if ( isAdjChar ( S ) == False ) : NEW_LINE INDENT return S NEW_LINE DEDENT if ( len ( S ) == 2 ) : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT rearrangeStringUtil ( N ) NEW_LINE S = S [ : : - 1 ] NEW_LINE rearrangeStringUtil ( N ) NEW_LINE if ( isAdjChar ( S ) == False ) : NEW_LINE INDENT return S NEW_LINE DEDENT return " - 1" NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = len ( S ) NEW_LINE print ( rearrangeString ( N ) ) NEW_LINE DEDENT