Maximized partitions of a string such that each character of the string appears in one substring | C ++ program for the above approach ; Function to print all the substrings ; Stores the substrings ; Stores last index of characters of string s ; Find the last position of each character in the string ; Update the last index ; Iterate the given string ; Get the last index of s [ i ] ; Extend the current partition characters last pos ; If the current pos of character equals the min pos then the end of partition ; Add the respective character first ; Store the partition 's  len and reset variables ; Update the minp and str ; Driver Code ; Input string ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void print_substring ( string s ) { int n = s . size ( ) ; string str = " " ; vector < int > ans ; if ( n == 0 ) { cout << " - 1" ; return ; } vector < int > last_pos ( 26 , -1 ) ; for ( int i = n - 1 ; i >= 0 ; -- i ) { if ( last_pos [ s [ i ] - ' a ' ] == -1 ) { last_pos [ s [ i ] - ' a ' ] = i ; } } int minp = -1 ; for ( int i = 0 ; i < n ; ++ i ) { int lp = last_pos [ s [ i ] - ' a ' ] ; minp = max ( minp , lp ) ; if ( i == minp ) { str += s [ i ] ; cout << str << ' ▁ ' ; minp = -1 ; str = " " ; } else { str += s [ i ] ; } } } int main ( ) { string S = " ababcbacadefegdehijhklij " ; print_substring ( S ) ; return 0 ; }