Count of Distinct Substrings occurring consecutively in a given String | Java program to implement the above approach ; Function to count the distinct substrings placed consecutively in the given string ; Length of the string ; If length of the string does not exceed 1 ; Initialize a DP - table ; Declaring ArrayList to store strings ; Iterate from end of the string ; Iterate backward until dp table is all computed ; If character at i - th index is same as character at j - th index ; Update dp [ i ] [ j ] based on previously computed value ; Otherwise ; Condition for consecutively placed similar substring ; Return the count ; Driver Code
import java . io . * ; import java . util . ArrayList ; class GFG { static int distinctSimilarSubstrings ( String str ) { int n = str . length ( ) ; if ( n <= 1 ) return 0 ; long dp [ ] [ ] = new long [ n + 1 ] [ n + 1 ] ; ArrayList < String > list = new ArrayList < String > ( ) ; for ( int j = n - 1 ; j >= 0 ; j -- ) { for ( int i = j - 1 ; i >= 0 ; i -- ) { if ( str . charAt ( i ) == str . charAt ( j ) ) { dp [ i ] [ j ] = dp [ i + 1 ] [ j + 1 ] + 1 ; } else { dp [ i ] [ j ] = 0 ; } if ( dp [ i ] [ j ] >= j - i ) { list . add ( str . substring ( j - i , i ) ) ; } } } return list . size ( ) ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; System . out . println ( distinctSimilarSubstrings ( str ) ) ; } }