text: Count of distinct characters in a substring by given range for Q queries | Java program for the naive approach ; Counter to count distinct char ; Initializing frequency array to count characters as the appear in subString S [ L : R ] ; Iterating over S [ L ] to S [ R ] ; Incrementing the count of s [ i ] character in frequency array ; If frequency of any character is > 0 then increment the counter ; Driver code
code: class GFG { static void findCount ( String s , int L , int R ) { int distinct = 0 ; int [ ] frequency = new int [ 26 ] ; for ( int i = L ; i <= R ; i ++ ) { frequency [ s . charAt ( i ) - ' a ' ] ++ ; } for ( int i = 0 ; i < 26 ; i ++ ) { if ( frequency [ i ] > 0 ) distinct ++ ; } System . out . print ( distinct + "NEW_LINE"); } public static void main ( String [ ] args ) { String s = " geeksforgeeksisa " + " computerscienceportal " ; int queries = 3 ; int Q [ ] [ ] = { { 0 , 10 } , { 15 , 18 } , { 12 , 20 } } ; for ( int i = 0 ; i < queries ; i ++ ) findCount ( s , Q [ i ] [ 0 ] , Q [ i ] [ 1 ] ) ; } }