Count number of equal pairs in a string | Java 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
import java . io . * ; class GFG { static int MAX = 256 ; static int countPairs ( String s ) { int cnt [ ] = new int [ MAX ] ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) cnt [ s . charAt ( i ) ] ++ ; int ans = 0 ; for ( int i = 0 ; i < MAX ; i ++ ) ans += cnt [ i ] * cnt [ i ] ; return ans ; } public static void main ( String [ ] args ) { String s = " geeksforgeeks " ; System . out . println ( countPairs ( s ) ) ; } }