In this HackerEarth Substrings problem solution You have a string S, but you like only special strings. So, you have to calculate the total number of special substrings in S.

A string T, of length L, is called special string, if either of the following property holds:
  1. All characters of the string T are same. for example, aaa
  2. The string has an odd length (i.e, L is odd) and all characters of T are same except the middle character, for example, aabaa.
Count the total number of special substrings in S.


HackerEarth Substrings problem solution


HackerEarth Substrings problem solution.

#include<bits/stdc++.h>
using namespace std;

//Constants:
#define N 1000005
#define ll long long
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define pritnf printf

ll le[N];
ll ri[N];

int main()
{
ll t,i=0,j,k,x,y,z,count=0,p,flag=0,ans=0,sum=0,l,n,m,max1,min1,pos,tmp,q;

//string s;

t=1;

while(t--)
{
string s;
cin >> s;
l=s.length();

ans=0;
//condition 1
count=1;
for(i=1;i<l;i++)
{
if(s[i]==s[i-1])
count++;
else
{
ans+=count*(count+1)/2;
count=1;
}
}
ans+=count*(count+1)/2;
//printf("%lld ",ans);

//condition 2
count=1;
for(i=1;i<l;i++)
{
if(s[i]==s[i-1])
count++;
else
{
le[i]=count;
count=1;
}
}

count=1;
for(i=l-2;i>=0;i--)
{
if(s[i]==s[i+1])
count++;
else
{
ri[i]=count;
count=1;
}
}

for(i=1;i<l-1;i++)
{
p=min(le[i],ri[i]);

if(s[i-1]==s[i+1] && s[i]!=s[i+1])
ans+=p;
//printf("%lld ",ans);
}

printf("%lld\n",ans);

}


return 0;
}