Check if one string can be converted to other using given operation | Java implementation of above approach ; Function that prints whether is it possible to make a String equal to T by performing given operations ; Base case , if we put the last character at front of A ; Base case , if we put the last character at back of A ; Condition if current sequence is matchable ; Condition for front move to ( i - 1 ) th character ; Condition for back move to ( i - 1 ) th character ; Condition if it is possible to make String A equal to String T ; Print final answer ; Driver Code
import java . util . * ; class GFG { static void twoStringsEquality ( String s , String t ) { int n = s . length ( ) ; int [ ] [ ] dp = new int [ n ] [ n + 1 ] ; if ( s . charAt ( n - 1 ) == t . charAt ( 0 ) ) dp [ n - 1 ] [ 1 ] = 1 ; if ( s . charAt ( n - 1 ) == t . charAt ( n - 1 ) ) dp [ n - 1 ] [ 0 ] = 1 ; for ( int i = n - 1 ; i > 0 ; i -- ) { for ( int j = 0 ; j <= n - i ; j ++ ) { if ( dp [ i ] [ j ] > 0 ) { if ( s . charAt ( i - 1 ) == t . charAt ( j ) ) dp [ i - 1 ] [ j + 1 ] = 1 ; if ( s . charAt ( i - 1 ) == t . charAt ( i + j - 1 ) ) dp [ i - 1 ] [ j ] = 1 ; } } } boolean ans = false ; for ( int i = 0 ; i <= n ; i ++ ) { if ( dp [ 0 ] [ i ] == 1 ) { ans = true ; break ; } } if ( ans == true ) System . out . print ( " Yes " + "NEW_LINE"); else System . out . print ( " No " + "NEW_LINE"); } public static void main ( String [ ] args ) { String S = " abab " ; String T = " baab " ; twoStringsEquality ( S , T ) ; } }