#P1533. 第2题-塔子哥的字符串(枚举)
题目描述
塔子哥有一个字符串 \(s\)。
现在,他想让你求一下这个串中首尾字符相同的子串数目。
输入描述
一行,一个只包括小写字母的字符串 \(s(1\leq |s|\leq 10^5)\)。
输出描述
一个整数,字符串中首尾字符相同的子串数目。
样例
输入
aaa
输出
6
说明
长度为 1 的三个子串 "a" 长度为 2 的两个子串 "aa" 长度为 3 的一个子串 "aaa"
首先这种字符串得题目,数据范围为\(10^5\)除了那种一眼题。
剩下可以思考这两种方向
1:二分
2;O(n*26),就是枚举每一种字符串,然后在枚举整个字符串长度
或者O(26),就是枚举每一种字符
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
const int maxn=1e5+100;
ll cnt[maxn],len=0;
char a[maxn];
int main(){
scanf("%s",a);
len=strlen(a);
for(int i=0;i<len;i++){
cnt[a[i]-'a']++;
}
ll ans=len;
for(int i=0;i<26;i++){
ans=ans+(cnt[i]*(cnt[i]-1)/2);
}
cout<<ans<<endl;
}