看懂这个样例很重要:
15
czddeneeeemigec
AC代码:
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<stdio.h>
#include<utility>
#include<cstring>
#include<queue>
#include<stack>
#include<unordered_map>
#include<set>
#define ll long long
const int MAX = 2e5 + 5;
int arr[MAX] = { 0 };
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while (t--)
{
memset(arr, 0, sizeof arr);
int n;
cin >> n;
string str;
cin >> str;
string msubstr;
//找到最大子序列 —— 遍历n^2超时
unordered_map<char, int>hash;
for (char x : str)
hash[x]++;
for (int i = 0; i < str.size(); i++)
{
int j = str[i] + 1;
for (; j <= 'z'; j++)
{
if (hash[j] != 0)
break;
}
hash[str[i]]--;
if (j <= 'z')continue;
arr[i] = 1;//标记为子串
msubstr += str[i];
}
//cout << "#### " << msubstr << endl;
//其实就是翻转啊
reverse(msubstr.begin(), msubstr.end());
auto it = msubstr.begin();
//改原串吧
for (int i = 0; i < str.size(); i++)
{
if (arr[i] == 1)
{
str[i] = *it;
it++;
}
}
//移动过才用比
int i = 1;
for (; i < str.size(); i++)
{
if (str[i] < str[i - 1])
break;
}
if (i != str.size())
cout << -1 << endl;
else
{
/*if (msubstr[0] == msubstr.back())
cout << 0 << endl;
else*/
//bdcdcb
int s = 1;
for (int j = msubstr.size() - 2; j >= 0; j--)
{
if (msubstr[j] == msubstr.back())
s++;
else
break;
}
cout << msubstr.size() - s << endl;
}
}
return 0;
}