Palindrome Index 1

 Given a string of lowercase letters in the range ascii[a-z], determine the index of a character that can be removed to make the string a palindrome. There may be more than one solution, but any will do. If the word is already a palindrome or there is no solution, return -1. Otherwise, return the index of a character to remove.



Example 1:

input : aaab

output:3

explanation: if we remove b than the string will be aaa which is palindrome ,b is in 3rd index.

Example 2:

input : baa

output:0

explanation: if we remove b than the string is aa which is palindrome , b is in 0th index


Example 3:

input : aaa

output:-1

explanation: it is a palindrome 



c++ implementation:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
  int t; cin>>t;
    while(t--) 
    {
        string s;
        cin>>s;
        string x;
        for(int i=s.length()-1;i>=0;i--)
            x=x+s[i];
        
        if(x==s)
        cout<<-1<<endl;
        else
        {
            int m=0;
            for(int i=s.length()-1;i>=0;i--)
            {
                if(s[i]!=s[m])
                {
                    if(s[i]==s[m+1])
                        cout<<m<<endl;
                    else
                        cout<<i<<endl;
                       
                       break;
                } 
                m++;
            }
            
        }

    }
    return 0;
}

Time Complexity: O(n)  ,where n is the length of the string



No comments

darkmode