Minimum substring removals required to make all remaining characters of a string same | Java program to implement the above approach ; Function to count minimum operations required to make all characters equal by repeatedly removing subString ; Remove consecutive duplicate characters from str ; Stores length of the String ; Stores frequency of each distinct characters of the String str ; Iterate over all the characters of the String str ; Update frequency of str [ i ] ; Decrementing the frequency of the String str [ 0 ] ; Decrementing the frequency of the String str [ N - 1 ] ; Stores the required count ; Iterate over all characters of the String str ; Update ans ; Driver Code ; Given String
import java . util . * ; class GFG { static void minOperationNeeded ( char [ ] str ) { str = modstring ( str ) ; int N = str . length ; int res [ ] = new int [ 256 ] ; for ( int i = 0 ; i < N ; ++ i ) { res [ str [ i ] ] += 1 ; } res [ str [ 0 ] ] -= 1 ; res [ str [ N - 1 ] ] -= 1 ; int ans = Integer . MAX_VALUE ; for ( int i = 0 ; i < N ; ++ i ) { ans = Math . min ( ans , res [ str [ i ] ] ) ; } System . out . print ( ( ans + 1 ) + "NEW_LINE"); } private static char [ ] modstring ( char [ ] str ) { String s = " " ; boolean b = true ; for ( int i = 1 ; i < str . length ; ++ i ) { if ( str [ i - 1 ] != str [ i ] ) b = true ; if ( b ) { s += str [ i - 1 ] ; b = false ; } } return s . toCharArray ( ) ; } public static void main ( String [ ] args ) { String str = " ABCDABCDABCDA " ; minOperationNeeded ( str . toCharArray ( ) ) ; } }