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
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 ] ) { swap ( s [ i ] , s [ j ] ) ; i ++ ; j = s . length ( ) - 1 ; } else { j -- ; } } if ( s . length ( ) % 2 != 0 ) { int mid = s . length ( ) / 2 ; if ( check [ mid ] == s [ mid ] ) { for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( check [ i ] != s [ mid ] && s [ i ] != s [ mid ] ) { swap ( s [ i ] , s [ mid ] ) ; break ; } } } } bool ok = true ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( check [ i ] == s [ i ] ) { ok = false ; break ; } } if ( ok ) cout << s ; else cout << -1 ; } int main ( ) { string S = " geek " ; findAnagram ( S ) ; return 0 ; }