yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #318 Maximum Product of Word Lengths #185

Open yokostan opened 5 years ago

yokostan commented 5 years ago
class Solution {
    public int maxProduct(String[] words) {
        int res = 0;
        int n = words.length;
        int[] masks = new int[n];

        for (int i = 0; i < n; i++) {
            int val = 0;
            for (int j = 0; j < words[i].length(); j++) {
                val |= 1<<(words[i].charAt(j)-'a');
            }
            masks[i] = val;
            //'|=' is similar to '+=', this part is actually masks[i] = masks[i] | 1 << (c - 'a') 
            //thus we add all overlapping 1s in our left shifted bits, like (left shifted bit)a | (bit)b = ab
            //masks is somehow like mapping our string characters to a 32 bit integer
        }

        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if ((masks[i] & masks[j]) == 0) {
                    res = Math.max(res, words[i].length() * words[j].length());
                }
            }
        }

        return res;
    }
}