Problem Statement
You are given a function f(x) , where f(x) is 1 if the first and last characters of string x are equal; else it is 0 .
You are given a stringS and you have to find the sum of f(x) for all substrings x of given string S .
You are given a string
Note: A substring is a contiguous slice of string S[i:j] such that i≤j . It is a contiguous slice of the original string.
Input Format
The first line contains an integerN , length of S .
The second line contains a stringS . S will contain only lower case characters (a−z) .
The first line contains an integer
The second line contains a string
Constraints
1≤|S|≤106
1≤|x|
Output Format
Print the required answer.
Print the required answer.
Sample Input
7
ababaca
Sample Output
14
Explanation
f("a")=1 , f("aba")=1 , f(“abaca”)=1 but f(“ab”)=0 , (“bac”)=0 . Hence counting all substrings we get 14
The 14 substring are
a - 4(times)
b - 2
c - 1
aba - 2
bab - 1
aca - 1
ababa - 1
abaca - 1
The 14 substring are
a - 4(times)
b - 2
c - 1
aba - 2
bab - 1
aca - 1
ababa - 1
abaca - 1
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
long int input,i,hash[26]={0},ans=0;
scanf("%ld",&input);
char a[input];
scanf("%s",a);
for(i=0;i<input;i++)
{
hash[(int)a[i]-97]++;
}
for(i=0;i<26;i++)
{
if(a[i]>0)
{
ans=ans+((hash[i]*(hash[i]+1))/2);
}
}
printf("%ld",ans);
return 0;
}