We compare two end' (current) chars and the key is how to check when there's a mismatch - DFS.
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <memory.h> using namespace std; bool isPalin(char *in, int i, int j) { if (i == j) return true; if (*(in + i) != *(in + j)) return false; else { if (i == j - 1) return true; else return isPalin(in, i + 1, j - 1); } } int main() { int cnt; cin >> cnt; while (cnt--) { char in[100006] = {0}; cin >> in; size_t len = strlen(in); int ret = -1; int i = 0, j = len - 1; while (i < j) { if (in[i] == in[j]) { i++; j--; } else { if (isPalin(in, i + 1, j)) { ret = i; break; } else { ret = j; break; } } } cout << ret << endl; } return 0; }