1020 Delete At Most Two Characters(35 分)
Given a string which contains only lower case English letters, how many different strings you can get after deleting AT MOST TWO characters in it?
Input Specification:
Each input file contains one test case, which gives the string whose length is in [3,10
6
].
Output Specification:
Print in a line the number of different strings you can get after deleting at most 2 characters.
Sample Input:
ababcc
Sample Output:
15
Hint:
Deleting 0 character gets ababcc.
Deleting 1 character gets babcc, aabcc, abbcc, abacc and ababc.
Deleting 2 character gets abcc, bbcc, bacc, babc, aacc, aabc, abbc, abac and abab.
倒着扫一遍后缀相同的值
正向再扫一遍就行了。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define N (int)2e6+10
char str[N];
int post[N];
int main(void)
{
scanf("%s", str+1);
int i, j;
ll res = 1;
int len = strlen(str+1);
post[len] = 1;
for (i = len; i >= 2; i--)
{
if (str[i] != str[i-1]) post[i-1] = post[i]+1;
else post[i-1] = post[i];
}
for (i = 1; i <= len; i++)
{
if (str[i] == str[i-1]) continue;
res += post[i+1];
if (i >= 2 && str[i-1] == str[i+1] || str[i-1] == str[i] && str[i] == str[i+1]) res--;
}
res += post[1];
cout << res;
}