Find an anagram of given String having different characters at corresponding indices | Java 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
import java . io . * ; 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 . charAt ( i ) != s . charAt ( j ) && check . charAt ( i ) != s . charAt ( j ) && check . charAt ( j ) != s . charAt ( i ) ) { char temp = s . charAt ( i ) ; s = s . substring ( 0 , i ) + s . charAt ( 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 . charAt ( mid ) == s . charAt ( mid ) ) { for ( i = 0 ; i < s . length ( ) ; i ++ ) { if ( check . charAt ( i ) != s . charAt ( mid ) && s . charAt ( i ) != s . charAt ( mid ) ) { char temp = s . charAt ( i ) ; s = s . substring ( 0 , i ) + s . charAt ( mid ) + s . substring ( i + 1 ) ; s = s . substring ( 0 , mid ) + temp + s . substring ( mid + 1 ) ; break ; } } } } boolean ok = true ; for ( i = 0 ; i < s . length ( ) ; i ++ ) { if ( check . charAt ( i ) == s . charAt ( i ) ) { ok = false ; break ; } } if ( ok ) System . out . println ( s ) ; else System . out . println ( - 1 ) ; } public static void main ( String [ ] args ) { String S = " geek " ; findAnagram ( S ) ; } }