Count substrings with same first and last characters

We are given a string S, we need to find count of all contiguous substrings starting and ending with same character.
Examples :
Input  : S = "abcab"
Output : 7
There are 15 substrings of "abcab"
a, ab, abc, abca, abcab, b, bc, bca
bcab, c, ca, cab, a, ab, b
Out of the above substrings, there 
are 7 substrings : a, abca, b, bcab, 
c, a and b.

Input  : S = "aba"
Output : 4
The substrings are a, b, a and aba
 The answer just depends on frequencies of characters in the original string.
 For example in string abcab, frequency of ‘a’ is 2 and substrings contributing to answer
 are a, abca and a respectively, a total of 3, which is calculated by (frequency of ‘a’+1)C2.

PROGRAM:

using namespace std;
#include <bits/stdc++.h>
const int MAX=26;
int check(string s){
    int result = 0;
    int c[MAX] = {0};
    for(int i=0;i<s.size();i++)
        c[s[i]-'a']++;
    for(int i=0;i<MAX;i++){
        result = result + c[i]*(c[i]+1)/2;
    }
    return result;
}
main(){
    string s("abcba");
    cout<<check(s);
}

OUTPUT: 7

Comments

Popular Posts