Minimize length of a string by removing suffixes and prefixes of same characters | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minLength ( string s ) { int i = 0 , j = s . length ( ) - 1 ; for ( ; i < j && s [ i ] == s [ j ] ; ) { char d = s [ i ] ; while ( i <= j && s [ i ] == d ) i ++ ; while ( i <= j && s [ j ] == d ) j -- ; } return j - i + 1 ; } int main ( ) { string S = " aacbcca " ; cout << minLength ( S ) ; }