Minimum operation require to make first and last character same | Java program to find minimum operation require to make first and last character same ; Return the minimum operation requires to make string first and last character same . ; Store indexes of first occurrences of characters . ; Initialize all the elements to - 1 ; Initialize result ; Traverse through all characters ; Find first occurrence ; Update result for subsequent occurrences ; Driven Program
import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static final int MAX = 256 ; static int minimumOperation ( String s ) { int n = s . length ( ) ; Vector < Integer > first_occ = new Vector < Integer > ( ) ; for ( int i = 0 ; i < MAX ; i ++ ) first_occ . add ( i , - 1 ) ; int res = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { int x = ( int ) s . charAt ( i ) ; if ( first_occ . elementAt ( x ) == - 1 ) first_occ . set ( x , i ) ; else { int last_occ = ( n - i - 1 ) ; res = Math . min ( res , first_occ . get ( x ) + last_occ ) ; } } return res ; } public static void main ( String args [ ] ) { String s = " bacdefghipalop " ; System . out . println ( minimumOperation ( s ) ) ; } }