Length of all prefixes that are also the suffixes of given string | Java program for the above approach ; Function to find the length of all prefixes of the given string that are also suffixes of the same string ; Stores the prefix string ; Traverse the string S ; Add the current character to the prefix string ; Store the suffix string ; Check if both the strings are equal or not ; Driver Code
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void countSamePrefixSuffix ( String s , int n ) { String prefix = " " ; for ( int i = 0 ; i < n - 1 ; i ++ ) { prefix += s . charAt ( i ) ; String suffix = s . substring ( n - 1 - i , n ) ; if ( prefix . equals ( suffix ) ) { System . out . print ( prefix . length ( ) + " ▁ " ) ; } } } public static void main ( String [ ] args ) { String S = " ababababab " ; int N = S . length ( ) ; countSamePrefixSuffix ( S , N ) ; } }