Count of triplets from the given string with non | Java program to count of triplets from the given string with non - equidistant characters ; Function to count valid triplets ; Store frequencies of a , b and c ; If the current letter is ' a ' ; If the current letter is ' b ' ; If the current letter is ' c ' ; Calculate total no of triplets ; Subtract invalid triplets ; Driver code
import java . util . * ; class GFG { static void CountValidTriplet ( String s , int n ) { int count_a = 0 , count_b = 0 , count_c = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . charAt ( i ) == ' a ' ) count_a ++ ; if ( s . charAt ( i ) == ' b ' ) count_b ++ ; if ( s . charAt ( i ) == ' c ' ) count_c ++ ; } int Total_triplet = count_a * count_b * count_c ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( ( 2 * j - i ) < n && s . charAt ( j ) != s . charAt ( i ) && s . charAt ( j * 2 - i ) != s . charAt ( j ) && s . charAt ( 2 * j - i ) != s . charAt ( i ) ) Total_triplet -- ; } } System . out . println ( Total_triplet ) ; } public static void main ( String [ ] args ) { String s = " abcbcabc " ; int n = s . length ( ) ; CountValidTriplet ( s , n ) ; } }