Check if a string is a scrambled form of another string | Java program to check if a given string is a scrambled form of another string ; Strings of non - equal length cant ' be scramble strings ; Empty strings are scramble strings ; Equal strings are scramble strings ; Converting string to character array ; Checking condition for Anagram ; Check if S2 [ 0. . . i ] is a scrambled string of S1 [ 0. . . i ] and if S2 [ i + 1. . . n ] is a scrambled string of S1 [ i + 1. . . n ] ; Check if S2 [ 0. . . i ] is a scrambled string of S1 [ n - i ... n ] and S2 [ i + 1. . . n ] is a scramble string of S1 [ 0. . . n - i - 1 ] ; If none of the above conditions are satisfied ; Driver Code
import java . util . * ; class GFG { static boolean isScramble ( String S1 , String S2 ) { if ( S1 . length ( ) != S2 . length ( ) ) { return false ; } int n = S1 . length ( ) ; if ( n == 0 ) { return true ; } if ( S1 . equals ( S2 ) ) { return true ; } char [ ] tempArray1 = S1 . toCharArray ( ) ; char [ ] tempArray2 = S2 . toCharArray ( ) ; Arrays . sort ( tempArray1 ) ; Arrays . sort ( tempArray2 ) ; String copy_S1 = new String ( tempArray1 ) ; String copy_S2 = new String ( tempArray2 ) ; if ( ! copy_S1 . equals ( copy_S2 ) ) { return false ; } for ( int i = 1 ; i < n ; i ++ ) { if ( isScramble ( S1 . substring ( 0 , i ) , S2 . substring ( 0 , i ) ) && isScramble ( S1 . substring ( i , n ) , S2 . substring ( i , n ) ) ) { return true ; } if ( isScramble ( S1 . substring ( n - i , n ) , S2 . substring ( 0 , i ) ) && isScramble ( S1 . substring ( 0 , n - i ) , S2 . substring ( i , n ) ) ) { return true ; } } return false ; } public static void main ( String [ ] args ) { String S1 = " coder " ; String S2 = " ocred " ; if ( isScramble ( S1 , S2 ) ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } }