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 i, j, a, b;for (i = 0, j = l - 1; i < l; i++, j--){if (s[i] != s[j])break;}if (i > j)return -1;for (a = i + 1, b = j; a < j && b > i + 1; a++, b--){if (s[a] != s[b])return j;}return i;}int main(){int q = 3;vector<string> queries = {"aaab", "baa", "aaa"};for (int i = 0; i < q; i++){string s = queries[i];cout << palindromeIndex(s) << "\n";}return 0;}
No comments:
Post a Comment