Check if count of substrings in S with string S1 as prefix and S2 as suffix is equal to that with S2 as prefix and S1 as suffix | Java program for the above approach ; Function to count number of substrings that starts with string S1 and ends with string S2 ; Stores the length of each string ; Stores the count of prefixes as S1 and suffixes as S2 ; Traverse string S ; Find the prefix at index i ; Find the suffix at index i ; If the prefix is S1 ; If the suffix is S2 ; Return the count of substrings ; Function to check if the number of substrings starts with S1 and ends with S2 and vice - versa is same or not ; Count the number of substrings ; Print the result ; Driver Code
class GFG { static int countSubstrings ( String S , String S1 , String S2 ) { int N = S . length ( ) ; int N1 = S1 . length ( ) ; int N2 = S2 . length ( ) ; int count = 0 , totalcount = 0 ; for ( int i = 0 ; i < N ; i ++ ) { String prefix = S . substring ( i , ( i + N1 < N ) ? ( i + N1 ) : N ) ; String suffix = S . substring ( i , ( i + N2 < N ) ? ( i + N2 ) : N ) ; if ( S1 . equals ( prefix ) ) count ++ ; if ( S2 . equals ( suffix ) ) totalcount += count ; } return totalcount ; } static void checkSubstrings ( String S , String S1 , String S2 ) { int x = countSubstrings ( S , S1 , S2 ) ; int y = countSubstrings ( S , S2 , S1 ) ; if ( x == y ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } public static void main ( String [ ] args ) { String S = " opencloseopencloseopen " ; String S1 = " open " ; String S2 = " close " ; checkSubstrings ( S , S1 , S2 ) ; } }