318. Maximum Product of Word Lengths - cocoder39/coco39_LC GitHub Wiki

318. Maximum Product of Word Lengths

an interesting idea here is transforming string to 26-bit int, so we can use & operation from int to check if there is intersection between two strings.

O(n^2)

int maxProduct(vector<string>& words) {
        int res = 0;
        int sz = words.size();
        vector<int> mask(sz);
        
        for (int i = 0; i < sz; i++) {
            for (char c : words[i])
                mask[i] |= 1 << (c - 'a'); //transform word to 26-bit int, ignoring repeated char
            for (int j = 0; j < i; j++) {
                if ((mask[i] & mask[j]) == 0) 
                    res = max(res, (int)words[i].length() * (int)words[j].length());
            }
        }
        return res;
    }
⚠️ **GitHub.com Fallback** ⚠️