Posted on

Description

Submission

class Solution {
public:
    bool checkPalindromeFormation(string a, string b) {
        int n = a.length();
        
        int aBeg = -1, bEnd = n;
        for(; a[aBeg+1] == b[bEnd-1]; aBeg++, bEnd--);
        
        // cout << aBeg << " "<< bEnd << endl;
        
        if(aBeg >= bEnd - 2) return true;
        else {
            bool aPossible = true;
            bool bPossible = true;
            for(int i = aBeg + 1, j = bEnd - 1; i <= j; ++i, --j) {
                if(a[i] != a[j]) aPossible = false;
                if(b[i] != b[j]) bPossible = false;
                if(!aPossible && !bPossible) break;
            }
            if(aPossible || bPossible) return true;
        }
        
        int bBeg = -1, aEnd = n;
        for(; a[aEnd-1] == b[bBeg+1]; bBeg++, aEnd--);
        // cout << bBeg << " "<< aEnd << endl;
        
        if(bBeg >= aEnd - 2) return true;
        else {
            bool aPossible = true;
            bool bPossible = true;
            for(int i = bBeg + 1, j = aEnd - 1; i <= j; ++i, --j) {
                if(a[i] != a[j]) aPossible = false;
                if(b[i] != b[j]) bPossible = false;
                if(!aPossible && !bPossible) break;
            }
            if(aPossible || bPossible) return true;
        }
        
        return false;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *