Count of substrings having all distinct characters | Java program to implement the above appraoach ; Function to count total number of valid subStrings ; Stores the count of subStrings ; Stores the frequency of characters ; Initialised both pointers to beginning of the String ; If all characters in subString from index i to j are distinct ; Increment count of j - th character ; Add all subString ending at j and starting at any index between i and j to the answer ; Increment 2 nd pointer ; If some characters are repeated or j pointer has reached to end ; Decrement count of j - th character ; Increment first pointer ; Return the final count of subStrings ; Driver Code
import java . util . * ; class GFG { static int countSub ( String str ) { int n = ( int ) str . length ( ) ; int ans = 0 ; int [ ] cnt = new int [ 26 ] ; int i = 0 , j = 0 ; while ( i < n ) { if ( j < n && ( cnt [ str . charAt ( j ) - ' a ' ] == 0 ) ) { cnt [ str . charAt ( j ) - ' a ' ] ++ ; ans += ( j - i + 1 ) ; j ++ ; } else { cnt [ str . charAt ( i ) - ' a ' ] -- ; i ++ ; } } return ans ; } public static void main ( String [ ] args ) { String str = " gffg " ; System . out . print ( countSub ( str ) ) ; } }