Codeforces Round #750 (Div. 2) C. Grandma Capa Knits a Scarf

【题目大意】

  输入一个字符串。执行任意次【删除同种字符】操作使其成为回文串。可以实现输出最小操作次数,不然输出-1.

【思路】

  用双指针 i, j  指向字符串的头尾。

  遍历26个字母,将每个字母当做应该删的【同种字符】‘p’。时间复杂度o(26n)。

  1.    s【i】==s【j】   外围相等 , 不影响回文的结果 。

  2.    s【i】!=s【j】 

      a.       s[i]=='p'     ||   s【j】==‘p’  该删除,看后续会不会形成回文

      b.  s【i】!=‘p’&& s【j】!=‘p’  说明这个组不成回文,直接退出匹配循环。

 

【代码】

#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <bitset>
#include <cstdlib>
#include <cmath>
#include <set>

#define ms(a, b) memset(a,b,sizeof(a))
#define fast ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define ll long long
#define ull unsigned long long
#define rep(i, a, b)  for(ll i=a;i<=b;i++)
#define lep(i, a, b)  for(ll i=a;i>=b;i--)
#define endl '\n'
#define pii pair<int, int>
#define pll pair<ll, ll>
#define vi  vector<ll>
#define vpi vector<pii>
#define vpl vector<pll>
#define mi  map<ll,ll>
#define all(a)  (a).begin(),(a).end()
#define gcd __gcd
#define pb push_back
#define mp make_pair
#define lb lower_bound
#define ub upper_bound

#define ff first
#define ss second
#define test4(x, y, z, a) cout<<"x is "<<x<<"        y is "<<y<<"        z is "<<z<<"        a is "<<a<<endl;
#define test3(x, y, z) cout<<"x is "<<x<<"        y is "<<y<<"        z is "<<z<<endl;
#define test2(x, y) cout<<"x is "<<x<<"        y is "<<y<<endl;
#define test1(x) cout<<"x is "<<x<<endl;
using namespace std;
const int N = 100010;
const int maxx = 0x3f3f3f;
const int mod = 1e9 + 7;
const int minn = -0x3f3f3f;
const int M = 2 * N;
ll T, n, m;
char s[N];
void solve() {
    cin>>n;
    cin>>s+1;
    ll ans = maxx;
    for ( int i=1;i<=26;i++){
        char p = 'a'+i-1;
        ll d=0;int l=1,r=n;
        while ( l<=r ){
            if ( s[l]==s[r] )   {l++;r--;}
            else {
                if ( s[l]==p )  {l++;d++ ;}
                else if ( s[r]==p ) {r--;d++;}
                else break;
            }
        }
        if ( l>r )  { ans = min(d,ans);}
    }
    if ( ans!= maxx  )     cout<<ans<<endl;
    else cout<<-1<<endl;return ;

}

int main() {
    fast;
    cin >> T;
    while (T--) {
        solve();
    }
    return 0;
}
View Code

 

posted @ 2022-03-10 20:51  Pan_c  阅读(33)  评论(0)    收藏  举报