Check if a given string can be converted to another by given possible swaps | Java program to implement the above approach ; Stores length of str1 ; Stores length of str2 ; Stores distinct characters of str1 ; Stores distinct characters of str2 ; Stores frequency of each character of str1 ; Traverse the String str1 ; Update frequency of str1 [ i ] ; Traverse the String str1 ; Insert str1 [ i ] into st1 ; Traverse the String str2 ; Insert str1 [ i ] into st1 ; If distinct characters in str1 and str2 are not same ; Stores frequency of each character of str2 ; Traverse the String str2 ; Update frequency of str2 [ i ] ; Sort hash1 [ ] array ; Sort hash2 [ ] array ; Traverse hash1 [ ] and hash2 [ ] ; If hash1 [ i ] not equal to hash2 [ i ] ; Driver Code
import java . util . * ; class GFG { static boolean checkStr1CanConStr2 ( String str1 , String str2 ) { int N = str1 . length ( ) ; int M = str2 . length ( ) ; HashSet < Integer > st1 = new HashSet < > ( ) ; HashSet < Integer > st2 = new HashSet < > ( ) ; int hash1 [ ] = new int [ 256 ] ; for ( int i = 0 ; i < N ; i ++ ) { hash1 [ str1 . charAt ( i ) ] ++ ; } for ( int i = 0 ; i < N ; i ++ ) { st1 . add ( ( int ) str1 . charAt ( i ) ) ; } for ( int i = 0 ; i < M ; i ++ ) { st2 . add ( ( int ) str2 . charAt ( i ) ) ; } if ( ! st1 . equals ( st2 ) ) { return false ; } int hash2 [ ] = new int [ 256 ] ; for ( int i = 0 ; i < M ; i ++ ) { hash2 [ str2 . charAt ( i ) ] ++ ; } Arrays . sort ( hash1 ) ; Arrays . sort ( hash2 ) ; for ( int i = 0 ; i < 256 ; i ++ ) { if ( hash1 [ i ] != hash2 [ i ] ) { return false ; } } return true ; } public static void main ( String [ ] args ) { String str1 = " xyyzzlll " ; String str2 = " yllzzxxx " ; if ( checkStr1CanConStr2 ( str1 , str2 ) ) { System . out . print ( " True " ) ; } else { System . out . print ( " False " ) ; } } }