We record the position for ones and zeros, then count the number of ones in t, the goal is to match the 1’s in t to some positions in s.

The stategy is to (1) mathc the zeros from MSB, and (2) match the zeros from LSB, since matching zeros would increase the value, so we want to do this from MSB, and for mathcing ones we decreas the value so we want to do this from LSB.

Code

class Solution {
public:
    string maximumXor(string s, string t) {
        int n = s.size();
        vector<int> zeros;
        vector<int> ones;
        for(int i = 0 ; i < n ; ++i) {
            if(s[i] == '1') {
                ones.push_back(i);
            } else {
                zeros.push_back(i);
            }
        }

        // number of ones in t
        int revertCnt = 0;
        for(int i = 0 ; i < n ; ++i) {
            if(t[i] == '1') ++revertCnt;
        }

        // fill one from MSB
        if(revertCnt < zeros.size()) {
            for(int i = 0 ; i < revertCnt ; ++i) s[zeros[i]] = '1';
            return s;
        } else {
            for(int i = 0 ; i < zeros.size() ; ++i) s[zeros[i]] = '1';
            revertCnt -= zeros.size();
        }

        // remove 1 from LSB
        if(revertCnt == 0) return s;
        int sz = ones.size();
        for(int i = 0 ; i < revertCnt ; ++i) {
            s[ones[sz-1-i]] = '0';
        }
        return s;
    }
};