题目
#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
void solve(){
int n;
string s;
cin >> n >> s;
s = ' ' + s;
vector<int> vec;
vec.push_back(n);
for(int i = n - 1; i >= 1; i--){
if(s[i] >= s[vec.back()]) vec.push_back(i);//字典序最大的子序列一定是单调不增的
}
reverse(vec.begin(), vec.end());
int cnt = 0;
int res = 0;
string t;
for(auto x : vec){
if(s[x] == s[vec[0]]) cnt++;
t += s[x];
}
int m = vec.size();
res = m - cnt;
reverse(t.begin(), t.end());
for(int i = 0; i < m; i++){
int pos = vec[i];
char ch = t[i];
s[pos] = ch;
}
if(is_sorted(s.begin() + 1, s.end())){
cout << res << '\n';
}
else cout << "-1\n";
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int T;
cin >> T;
while(T--){
solve();
}
return 0;
}