Lengths of maximized partitions of a string such that each character of the string appears in one substring | 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 ; Given String str ; Function Call
function partitionString ( s ) { let n = s . length ; let ans = [ ] ; if ( n == 0 ) { document . write ( " " ) ; return ; } let last_pos = Array ( 26 ) . fill ( - 1 ) ; for ( let i = n - 1 ; i >= 0 ; -- i ) { if ( last_pos [ s [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ] == - 1 ) { last_pos [ s [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ] = i ; } } let minp = - 1 , plen = 0 ; for ( let i = 0 ; i < n ; ++ i ) { let lp = last_pos [ s [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ] ; minp = Math . max ( minp , lp ) ; ++ plen ; if ( i == minp ) { ans . push ( plen ) ; minp = - 1 ; plen = 0 ; } } for ( let i = 0 ; i < ans . length ; i ++ ) { document . write ( ans [ i ] + " " ) ; } } let str = " " ; partitionString ( str ) ;