Plzz help me solve this :)?

A string(small alphabets) is given. You can swap any two alphabets ONLY ONCE and u have to give the max length of a palindromic substring possible.

Here is my code for your reference(It gives wrong answer for “chiaki”) :
#include
#include
using namespace std;
int palindrome(string s)
{

int l=s.size();string temp=s;
for(int i=0;i<=l/2;i++)

{

swap(s[i],s[l-i-1]);

}

if(temp==s){return 1;}

else{return 0;}

}

int search(string s)

{

int lmax=1;

for(int i=0;i<s.size();i++)

{

for(int j=1;j<=s.size()-i;j++)

{

if(palindrome(s.substr(i,j)) && lmax<=j){lmax=j;}

}

}

return lmax;

}

int main()

{

string s;

cin>>s; string temp=s;int lmax=1;

for(int i=0;i<s.size();i++)

{ s=temp;

for(int j=0;j<s.size();j++)

{s=temp;

swap(s[i],s[j]);int l=search(s);

if(l>=lmax){lmax=l;}

}

}
cout<<endl<<endl<<lmax;

return 0;
}

Your Palindrome function won’t work in string length 2 case.

As you’ll swap both the times and would result in the same number as before. So it’ll always show palindrome in length 2 case. Just remove the “=” sign in the loop.

Remaining seems to be correct except the final printing statement. I think mostly the problem won’t ask for printing the answer after 2 new lines. Remove those 2 endls and print directly.

Also, to optimize the code you can change your O(n^3) complexity to O(n^2) to calculate the longest palindromic substring.

Provide the Question link if it still doesn’t work.

Thanks i got my mistake :slight_smile: