Minimize length of a string by removing suffixes and prefixes of same characters | Java program for the above approach ; Function to find the minimum length of the string after removing the same characters from the end and front of the two strings after dividing into 2 substrings ; Initialize two pointers ; Traverse the string S ; Current char on left pointer ; Shift i towards right ; Shift j towards left ; Return the minimum possible length of string ; Driver Code
import java . lang . * ; import java . util . * ; class GFG { static int minLength ( String s ) { int i = 0 , j = s . length ( ) - 1 ; for ( ; i < j && s . charAt ( i ) == s . charAt ( j ) ; ) { char d = s . charAt ( i ) ; while ( i <= j && s . charAt ( i ) == d ) i ++ ; while ( i <= j && s . charAt ( j ) == d ) j -- ; } return j - i + 1 ; } public static void main ( String [ ] args ) { String S = " aacbcca " ; System . out . println ( minLength ( S ) ) ; } }