Group all occurrences of characters according to first appearance | Java program to print all occurrences of every character together . ; Since only lower case characters are there ; Method to print the string ; Initialize counts of all characters as 0 ; Count occurrences of all characters in string ; Starts traversing the string ; Print the character till its count in hash array ; Make this character 's count value as 0. ; Driver method
class Test { static final int MAX_CHAR = 26 ; static void printGrouped ( String str ) { int n = str . length ( ) ; int count [ ] = new int [ MAX_CHAR ] ; for ( int i = 0 ; i < n ; i ++ ) count [ str . charAt ( i ) - ' a ' ] ++ ; for ( int i = 0 ; i < n ; i ++ ) { while ( count [ str . charAt ( i ) - ' a ' ] != 0 ) { System . out . print ( str . charAt ( i ) ) ; count [ str . charAt ( i ) - ' a ' ] -- ; } count [ str . charAt ( i ) - ' a ' ] = 0 ; } } public static void main ( String args [ ] ) { String str = new String ( " geeksforgeeks " ) ; printGrouped ( str ) ; } }