Count substrings having frequency of a character exceeding that of another character in a string | Java program for the above approach ; Function to find the number of substrings having the frequency of ' a ' greater than frequency of ' c ' ; Stores the size of the string ; Stores the resultant count of substrings ; Traverse the given string ; Store the difference between frequency of ' a ' and ' c ' ; Traverse all substrings beginning at index i ; If the frequency of ' a ' is greater than ' c ' ; Print the answer ; Drive Code
public class GFG { public static void countSubstrings ( String s ) { int n = s . length ( ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int cnt = 0 ; for ( int j = i ; j < n ; j ++ ) { if ( s . charAt ( j ) == ' a ' ) cnt ++ ; else if ( s . charAt ( j ) == ' c ' ) cnt -- ; if ( cnt > 0 ) { ans ++ ; } } } System . out . println ( ans ) ; } public static void main ( String args [ ] ) { String S = " abccaab " ; countSubstrings ( S ) ; } }