Substring score

Insert picture description here
Insert picture description here

Ideas

It can be enumerated and triple-cycled. In this way, n needs to be less than 100. Obviously it is not the
number of substrings contributed by each letter. Its subscript is the absolute value of the subscript of the same letter before and after the same letter. Multiply together, and then accumulate each letter is the answer
Insert picture description here

For example, for this string in the figure, count the number of contribution substrings of position 4
a. The subscript of the first a is 1, and the last one is 6 (4-1)*(6-4)=6.
Explain that 4-1 corresponds to With bca (No. 234) 6-4 corresponds to ab (No. 45)
. The substrings with bca as the starting position and ba as the ending position all contain only the 4th a, and all substrings only contain the 4th a,
that is For bca bcab ca cab a ab
Note the initial, there may not be the same letter before or after

Code

#include<iostream>
#include<string>
using namespace std;

const int N=1e5+5;
int pre[N],nex[N],a[27];
string s;

int main()
{
    
    
	cin>>s;
	s="0"+s;						//下标从1开始 
	int n=s.length()-1;				//长度 
	for(int i=1;i<=n;i++)			//寻找前一个相同字符下标 
	{
    
    
		int c=s[i]-'a';
		pre[i]=a[c];
		a[c]=i;
	}
	for(int i=0;i<26;i++)			//初始化,可能后边没有相同字符    寻找前一个时,未初始,因为a数组默然为0 
		a[i]=n+1;
	for(int i=n;i;i--)				//寻找后一个相同字符下标 
	{
    
    
		int c=s[i]-'a';
		nex[i]=a[c];
		a[c]=i;
	}
	long long int ans=0;
	for(int i=1;i<=n;i++)
		ans+=(long long)(i-pre[i])*(nex[i]-i);//相乘计算累加
	cout<<ans; 
	return 0;
}

Guess you like

Origin blog.csdn.net/m0_54621932/article/details/114035181