从后往前遍历,遍历到i位置时,统计大于i的字符中,有哪些字符是不等于s[i],并且数量大于等于2的。如果数量大雨等于2,那么这些字符都可以和i位置的字符组成abb的格式。
使用一个数组统计,从后往前遍历一遍既可得到答案。
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
string s;
cin >> s;
vector<int> a(26, 0);
long long ans = 0;
for (int i = n - 1; i >= 0; i--) {
for (int j = 0; j < 26; j++) {
if (j == s[i] - 'a') continue;
else if (a[j] >= 2)
ans += (a[j] * 1LL * (a[j] - 1)) / 2;
}
a[s[i] - 'a']++;
}
cout << ans << '\n';
}
// 64 位输出请用 printf("%lld")



京公网安备 11010502036488号