Count number of equal pairs in a string | CPP program to count the number of pairs ; Function to count the number of equal pairs ; Hash table ; Traverse the string and count occurrence ; Stores the answer ; Traverse and check the occurrence of every character ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX  256 NEW_LINE int countPairs ( string s ) { int cnt [ MAX ] = { 0 } ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) cnt [ s [ i ] ] ++ ; int ans = 0 ; for ( int i = 0 ; i < MAX ; i ++ ) ans += cnt [ i ] * cnt [ i ] ; return ans ; } int main ( ) { string s = " geeksforgeeks " ; cout << countPairs ( s ) ; return 0 ; }