class  Solution  { public  String  removeDuplicates ( String  s,  int  k)  { int  n= s. length ( ) ; char [ ] cs= s. toCharArray ( ) ; StringBuilder  res= new  StringBuilder ( ) ; res. append ( cs[ 0 ] ) ; Deque < Integer > = new  LinkedList < > ( ) ; st. addLast ( 1 ) ; for ( int  i= 1 ; i< n; i++ ) { res. append ( cs[ i] ) ; if ( res. length ( ) > 1 && res. charAt ( res. length ( ) - 1 ) == res. charAt ( res. length ( ) - 2 ) ) { st. addLast ( st. pollLast ( ) + 1 ) ; } else { st. addLast ( 1 ) ; } if ( st. peekLast ( ) == k) { res. delete ( res. length ( ) - k, res. length ( ) ) ; st. pollLast ( ) ; } } return  res. toString ( ) ; } public  String  removeDuplicates2 ( String  s,  int  k)  { int  n= s. length ( ) ; char [ ] cs= s. toCharArray ( ) ; StringBuilder  res= new  StringBuilder ( ) ; res. append ( cs[ 0 ] ) ; for ( int  i= 1 ; i< n; i++ ) { if ( ! res. isEmpty ( ) ) { int  cnt= 1 ; for ( int  j= 0 ; j< Math . min ( k- 1 ,  res. length ( ) ) ; j++ ) { if ( res. charAt ( res. length ( ) - 1 - j) == cs[ i] ) { cnt++ ; } } if ( cnt>= k) { int  size= res. length ( ) ; res. delete ( size- k+ 1 , size) ; } else { res. append ( cs[ i] ) ; } } else { res. append ( cs[ i] ) ; } } return  res. toString ( ) ; } 
} 
 
class  Solution  { public  String  removeDuplicateLetters ( String  s)  { int  n= s. length ( ) ; char [ ] cs= s. toCharArray ( ) ; StringBuilder  res= new  StringBuilder ( ) ; int [ ] set= new  int [ 26 ] ; boolean [ ] vis= new  boolean [ 26 ] ; for ( int  i= 0 ; i< n; i++ ) { char  c= cs[ i] ; set[ c- 'a' ] ++ ; } for ( int  i= 0 ; i< n; i++ ) { char  c= cs[ i] ; int  index= c- 'a' ; if ( ! vis[ index] ) { vis[ index] = true ; while ( res. length ( ) > 0 && res. charAt ( res. length ( ) - 1 ) > c) { int  tmp= res. charAt ( res. length ( ) - 1 ) - 'a' ; if ( set[ tmp] == 0 ) { break ; } vis[ tmp] = false ; res. deleteCharAt ( res. length ( ) - 1 ) ; } res. append ( c) ; } set[ index] -- ; } return  res. toString ( ) ; } 
}