Lengths of maximized partitions of a string such that each character of the string appears in one substring | Java 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
import java . util . * ; class GFG { static void partitionString ( String s ) { int n = s . length ( ) ; Vector < Integer > ans = new Vector < Integer > ( ) ; if ( n == 0 ) { System . out . print ( " - 1" ) ; return ; } int [ ] last_pos = new int [ 26 ] ; Arrays . fill ( last_pos , - 1 ) ; for ( int i = n - 1 ; i >= 0 ; -- i ) { if ( last_pos [ s . charAt ( i ) - ' a ' ] == - 1 ) { last_pos [ s . charAt ( i ) - ' a ' ] = i ; } } int minp = - 1 , plen = 0 ; for ( int i = 0 ; i < n ; ++ i ) { int lp = last_pos [ s . charAt ( 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 . size ( ) ; i ++ ) { System . out . print ( ans . get ( i ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { String str = " acbbcc " ; partitionString ( str ) ; } }