Find an anagram of given String having different characters at corresponding indices | C # program for the above approach ; Function to find anagram of string such that characters at the same indices are different ; Copying our original string for comparison ; Declaring the two pointers ; Checking the given condition ; When string length is odd ; The mid element ; If the characters are the same , then perform the swap operation as illustrated ; Check if the corresponding indices has the same character or not ; If string follows required condition ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static void findAnagram ( string s ) { string check = s ; int i = 0 , j = s . Length - 1 ; while ( i < s . Length && j >= 0 ) { if ( s [ i ] != s [ j ] && check [ i ] != s [ j ] && check [ j ] != s [ i ] ) { char temp = s [ i ] ; s = s . Substring ( 0 , i ) + s [ j ] + s . Substring ( i + 1 ) ; s = s . Substring ( 0 , j ) + temp + s . Substring ( j + 1 ) ; i ++ ; j = s . Length - 1 ; } else { j -- ; } } if ( s . Length % 2 != 0 ) { int mid = s . Length / 2 ; if ( check [ mid ] == s [ mid ] ) { for ( i = 0 ; i < s . Length ; i ++ ) { if ( check [ i ] != s [ mid ] && s [ i ] != s [ mid ] ) { char temp = s [ i ] ; s = s . Substring ( 0 , i ) + s [ mid ] + s . Substring ( i + 1 ) ; s = s . Substring ( 0 , mid ) + temp + s . Substring ( mid + 1 ) ; break ; } } } } bool ok = true ; for ( i = 0 ; i < s . Length ; i ++ ) { if ( check [ i ] == s [ i ] ) { ok = false ; break ; } } if ( ok ) Console . Write ( s ) ; else Console . Write ( - 1 ) ; } public static void Main ( ) { string S = " geek " ; findAnagram ( S ) ; } }