I tried to start from the center with i,i and i,i+1, and expand from both side. I use ignore to maintain if we need to expand from left or right, and use a while loop to do the expansion. When the character is mistmatch, we try to ignore the left (or right) and kept matching.

Notice that the ending condition for the while loop is one of the l and r pointer is out of bound, in this case, we may need to check if the ignore is not used and we can do one more futher expansion, we can add one to the length.

During review, ChatGPT suggested that I used expand0 function to do normal expansion, and expand1 function to do expansion with tolerrance, and it would call two expand0, in this case we might have a more readable code and would be more stable.

Code

class Solution {
public:
    int almostPalindromic(string s) {
        int n = s.size();
        int maxLen = 0;
        for(int i = 0 ; i < n ; ++i) {
            maxLen = max(maxLen, count(s, i, i, true));
            maxLen = max(maxLen, count(s, i, i, false));
            maxLen = max(maxLen, count(s, i, i+1, true));
            maxLen = max(maxLen, count(s, i, i+1, false));
        }
        return maxLen;
    }

    inline int count(const string& s, int l, int r, bool left) {
        int n = s.size();
        bool ignore = true;
        while(l >= 0 && r <= n-1) {
            if (s[l] == s[r]) {
                --l;
                ++r;
            } else if (ignore) {
                ignore = false;
                if(left) --l;
                else ++r;
            } else {
                break;
            }
        }
        int len = (r - l + 1 - 2);
        if(ignore && !(l == -1 && r == n)) ++len;
        return len;
    }
};