Check if two strings can be made equal by swapping one character among each other | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool canBeEqual ( string a , string b , int n ) { vector < char > A , B ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] != b [ i ] ) { A . push_back ( a [ i ] ) ; B . push_back ( b [ i ] ) ; } } if ( A . size ( ) == B . size ( ) and B . size ( ) == 0 ) return true ; if ( A . size ( ) == B . size ( ) and B . size ( ) == 2 ) { if ( A [ 0 ] == A [ 1 ] and B [ 0 ] == B [ 1 ] ) return true ; } return false ; } int main ( ) { string A = " SEEKSFORGEEKS " ; string B = " GEEKSFORGEEKG " ; if ( canBeEqual ( A , B , A . size ( ) ) ) printf ( " Yes " ) ; else printf ( " No " ) ; }