Minimum operation require to make first and last character same | Java program to find minimum operation require to make first and last character same ; Function to find minimum operation require to make first and last character same ; Base conditions ; If answer found ; If string is already visited ; Decrement ending index only ; Increment starting index only ; Increment starting index and decrement index ; Store the minimum value ; Driver code ; Function call
import java . io . * ; import java . util . * ; class GFG { static int MAX = Integer . MAX_VALUE ; static HashMap < String , Integer > m = new HashMap < > ( ) ; static int Min = Integer . MAX_VALUE ; static int minOperation ( String s , int i , int j , int count ) { if ( ( i >= s . length ( ) && j < 0 ) || ( i == j ) ) { return MAX ; } if ( s . charAt ( i ) == s . charAt ( j ) || ( count >= Min ) ) { return count ; } String str = String . valueOf ( i ) + " | " + String . valueOf ( j ) ; if ( ! m . containsKey ( str ) ) { if ( i >= s . length ( ) ) { m . put ( str , minOperation ( s , i , j - 1 , count + 1 ) ) ; } else if ( j < 0 ) { m . put ( str , minOperation ( s , i + 1 , j , count + 1 ) ) ; } else { m . put ( str , Math . min ( minOperation ( s , i , j - 1 , count + 1 ) , minOperation ( s , i + 1 , j , count + 1 ) ) ) ; } } if ( m . get ( str ) < Min ) { Min = m . get ( str ) ; } return m . get ( str ) ; } public static void main ( String [ ] args ) { String s = " bacdefghipalop " ; int ans = minOperation ( s , 0 , s . length ( ) - 1 , 0 ) ; if ( ans == MAX ) { System . out . println ( - 1 ) ; } else { System . out . println ( ans ) ; } } }