双指针。结合回文串的性质,对于最外面的两个端点,由于每次只可能删除同一种字符,那么如果内部的串可构成回文串,那么外部字符无关紧要,符合无后效性。

值得注意的一点是,双指针不一定两个指针都一起移动,需要每次都判断条件,并进行值的增减。

#include<cstdio>
#include<iostream>
using namespace std;
const int INF=2e9;
string s;

int getVal(char testChar){//需要减的数量,-1为不存在 
    int l=0,r=s.size()-1;
    int ans=0;
    while(r>l){
        if(s[l]==s[r]){//两端点字符相等
            l++;
            r--;
            continue;//不影响统计答案 
        }
        if(s[l]!=testChar&&s[r]!=testChar){//两端点字符都不是测试字符且不相同
            return -1;//不成立 
        }
        //两端点有一个是测试字符
        if(s[l]==testChar&&s[l]!=s[r]){
            l++;//转移端点
            ans++; 
            continue;
        }else if(s[r]==testChar&&s[l]!=s[r]){
            r--;//转移端点
            ans++; 
            continue;
        }
        
    }
    return ans;
}

int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        int n;
        scanf("%d",&n);
        cin>>s;
        int ans=-1;
        for(char i='a';i<='z';i++){
            int tmpAns=getVal(i);
            if(ans==-1){
                ans=tmpAns;
            }else{
                if(tmpAns!=-1){
                    ans=min(ans,tmpAns);
                }
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}