Posts

Search

I M12 - Power of a String

Power of string is the sum of square of frequency of different letters in the string. Given string only consists of lowercase English letters. Your task is to find the power of string.
Input Format
First line contains an integer for the number of test case. Each test case consists of length of the input string and the string.
Constraints
1 <= t <= 10. Input size of string length over all the test cases doesn't exceed 100000.
Output Format
For each test case print the power of string in a new line.
Sample Input 0
1
5
aabbc
Sample Output 0
9
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include<bits/stdc++.h>
using namespace std;
long long int fun(string str,int n)
{
    long long int ans=0;
    int c[26]={0};
    for(long long int i=0;i<n;i++){
        c[str[i]-'a']++;
       
    }
    for(int i=0;i<26;i++){
        ans+=pow(c[i],2);
    }
    return ans;
}
int main(){
    int tc;
    cin>>tc;
    while(tc--){
        long long int n;
        cin>>n;
        string str;
        cin>>str;
        cout<<fun(str,n)<<endl;
    }


    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
    return 0;
}