Different substrings in a string that start and end with given strings | Java program to find number of different sub strings ; function to return number of different sub - strings ; initially our answer is zero . ; find the length of given strings ; currently make array and initially put zero . ; find occurrence of " a " and " b " in string " s " ; We use a hash to make sure that same substring is not counted twice . ; go through all the positions to find occurrence of " a " first . ; if we found occurrence of " a " . ; then go through all the positions to find occurrence of " b " . ; if we do found " b " at index j then add it to already existed substring . ; if we found occurrence of " b " . ; now add string " b " to already existed substring . ; If current substring is not included already . ; put any non negative integer to make this string as already existed . ; make substring null . ; return answer . ; Driver Code
import java . util . HashSet ; class GFG { static int numberOfDifferentSubstrings ( String s , char a , char b ) { int ans = 0 ; int ls = s . length ( ) ; int [ ] x = new int [ ls ] ; int [ ] y = new int [ ls ] ; for ( int i = 0 ; i < ls ; i ++ ) { if ( s . charAt ( i ) == a ) x [ i ] = 1 ; if ( s . charAt ( i ) == b ) y [ i ] = 1 ; } HashSet < String > hash = new HashSet < > ( ) ; String curr_substr = " " ; for ( int i = 0 ; i < ls ; i ++ ) { if ( x [ i ] != 0 ) { for ( int j = i ; j < ls ; j ++ ) { if ( y [ j ] == 0 ) curr_substr += s . charAt ( i ) ; if ( y [ j ] != 0 ) { curr_substr += s . charAt ( j ) ; if ( ! hash . contains ( curr_substr ) ) ans ++ ; hash . add ( curr_substr ) ; } } curr_substr = " " ; } } return ans ; } public static void main ( String [ ] args ) { String s = " codecppforfood " ; char begin = ' c ' ; char end = ' d ' ; System . out . println ( numberOfDifferentSubstrings ( s , begin , end ) ) ; } }