Check if two strings can be made equal by swapping one character among each other | Java implementation of the approach ; Function that returns true if the string can be made equal after one swap ; A and B are new a and b after we omit the same elements ; Take only the characters which are different in both the strings for every pair of indices ; If the current characters differ ; The strings were already equal ; If the lengths of the strings are two ; If swapping these characters can make the strings equal ; Driver code
import java . util . * ; class GFG { static boolean canBeEqual ( char [ ] a , char [ ] b , int n ) { Vector < Character > A = new Vector < > ( ) ; Vector < Character > B = new Vector < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] != b [ i ] ) { A . add ( a [ i ] ) ; B . add ( b [ i ] ) ; } } if ( A . size ( ) == B . size ( ) && B . size ( ) == 0 ) return true ; if ( A . size ( ) == B . size ( ) && B . size ( ) == 2 ) { if ( A . get ( 0 ) == A . get ( 1 ) && B . get ( 0 ) == B . get ( 1 ) ) return true ; } return false ; } public static void main ( String [ ] args ) { char [ ] A = " SEEKSFORGEEKS " . toCharArray ( ) ; char [ ] B = " GEEKSFORGEEKG " . toCharArray ( ) ; if ( canBeEqual ( A , B , A . length ) ) System . out . printf ( " Yes " ) ; else System . out . printf ( " No " ) ; } }