Lengths of maximized partitions of a string such that each character of the string appears in one substring | C # program for the above approach ; Function to find the length of all partitions oof a String such that each characters occurs in a single subString ; Stores last index of String s ; Find the last position of each letter 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 ; Increase len of partition ; if the current pos of character equals the min pos then the end of partition ; Store the length ; Print all the partition lengths ; Driver Code ; Given String str ; Function Call
using System ; using System . Collections . Generic ; class GFG { static void partitionString ( String s ) { int n = s . Length ; List < int > ans = new List < int > ( ) ; if ( n == 0 ) { Console . Write ( " - 1" ) ; return ; } int [ ] last_pos = new int [ 26 ] ; for ( int i = 0 ; i < 26 ; ++ i ) { last_pos [ i ] = - 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 , plen = 0 ; for ( int i = 0 ; i < n ; ++ i ) { int lp = last_pos [ s [ i ] - ' a ' ] ; minp = Math . Max ( minp , lp ) ; ++ plen ; if ( i == minp ) { ans . Add ( plen ) ; minp = - 1 ; plen = 0 ; } } for ( int i = 0 ; i < ( int ) ans . Count ; i ++ ) { Console . Write ( ans [ i ] + " ▁ " ) ; } } public static void Main ( String [ ] args ) { String str = " acbbcc " ; partitionString ( str ) ; } }