Palindrome Index

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:

Input: q = 3, queries = {"aaab", "baa", "aaa"}

Output:

3 0 -1

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

int palindromeIndex(string s)
{
    int l = s.length();
    int ijab;
    for (i = 0j = l - 1i < li++, j--)
    {
        if (s[i] != s[j])
            break;
    }
    if (i > j)
        return -1;

    for (a = i + 1b = ja < j && b > i + 1a++, b--)
    {
        if (s[a] != s[b])
            return j;
    }
    return i;
}

int main()
{
    int q = 3;
    vector<stringqueries = {"aaab""baa""aaa"};

    for (int i = 0i < qi++)
    {
        string s = queries[i];
        cout << palindromeIndex(s<< "\n";
    }

    return 0;
}


No comments:

Post a Comment