#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while(t--)
{
int n;
cin >> n;
string s;
cin >> s;
vector<bool>visited(n, true);
int count = 0;
bool flag ;
// if string length is 2, checking it is
// palindrome or not
if( n == 2)
{
if( s[0] == s[1])
flag = true;
else
flag = false;
}
else
{
for( int i = 0, j = n-1 ; i < j; i++, j--)
{
flag = false;
//checking 1st and last character of string is
//same or not
if(s[i] != s[j])
{
// if 2nd character and last char of string is same and
// 1st two char are not swapped / visited then only
// swap them
if((s[i+1] == s[j]) && ( visited[i] && visited[i+1]) )
{
char temp = s[i+1];
s[i+1] = s[i];
s[i] = temp;
visited[i] = false;
visited[i+1] = false;
flag = true;
count++;
}
else
{
// if 2nd last and 1st char of the string is same
// and last and 2nd last char is not swapped/ visited
// then only swap them
if((s[j-1] == s[i]) && (visited[j] && visited[j-1]) )
{
char temp = s[j];
s[j] = s[j-1];
s[j-1] = temp;
visited[j] = false;
visited[j-1] = false;
flag = true;
count++;
}
}
}
else
flag = true;
// In 1 pass , we find that char can not be
// swapped, then come out of the loop and
// say NO.
if(!flag)
break;
}
}
if(flag)
{
cout << "YES"<<endl;
cout << count <<endl;
}
else
cout <<"NO"<<endl;
}
return 0;
}
I am getting WA for this code. I tried many test cases which are getting accepted.
Anyone help me in finding out what is wrong ? Thank you in advance.