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 | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 . substr ( i , N1 ) ; string suffix = S . substr ( i , N2 ) ; if ( S1 == prefix ) count ++ ; if ( S2 == suffix ) totalcount += count ; } return totalcount ; } void checkSubstrings ( string S , string S1 , string S2 ) { int x = countSubstrings ( S , S1 , S2 ) ; int y = countSubstrings ( S , S2 , S1 ) ; if ( x == y ) cout << " Yes " ; else cout << " No " ; } int main ( ) { string S = " opencloseopencloseopen " ; string S1 = " open " ; string S2 = " close " ; checkSubstrings ( S , S1 , S2 ) ; return 0 ; }