text: Check if a string can be made equal to another string by swapping or replacement of characters | Java program for the above approach ; Function to find if given Strings are same or not ; Base Condition ; Stores frequency of characters of the String str1 and str2 ; Traverse Strings str1 & str2 and store frequencies in a [ ] and b [ ] ; Check if both Strings have same characters or not ; If a character is present in one String and is not in another String , return false ; Sort the array a [ ] and b [ ] ; Check arrays a and b contain the same frequency or not ; If the frequencies are not the same after sorting ; At this point , str1 can be converted to str2 ; Driver Code
code: import java . util . * ; class GFG { static boolean sameStrings ( String str1 , String str2 ) { int N = str1 . length ( ) ; int M = str2 . length ( ) ; if ( N != M ) { return false ; } int [ ] a = new int [ 256 ] ; int [ ] b = new int [ 256 ] ; for ( int i = 0 ; i < N ; i ++ ) { a [ str1 . charAt ( i ) - ' a ' ] ++ ; b [ str2 . charAt ( i ) - ' a ' ] ++ ; } int i = 0 ; while ( i < 256 ) { if ( ( a [ i ] == 0 && b [ i ] == 0 ) || ( a [ i ] != 0 && b [ i ] != 0 ) ) { i ++ ; } else { return false ; } } Arrays . sort ( a ) ; Arrays . sort ( b ) ; for ( i = 0 ; i < 256 ; i ++ ) { if ( a [ i ] != b [ i ] ) return false ; } return true ; } public static void main ( String [ ] args ) { String S1 = " cabbba " , S2 = " abbccc " ; if ( sameStrings ( S1 , S2 ) ) System . out . print ( " YES " + "NEW_LINE"); else System . out . print ( " ▁ NO " + "NEW_LINE"); } }