September 15, 2019

318. Maximum Product of Word Lengths

318. Maximum Product of Word Lengths

class Solution {
    public int maxProduct(String[] words) {
        Arrays.sort(words, new Comparator<String>(){
            @Override
            public int compare(String s1, String s2) {
                return s2.length() - s1.length();
            }
        });
        
        int[] masks = new int[words.length];
        for (int i = 0; i < words.length; i++) {
            int mask = 0;
            String word = words[i];
            for (int j = 0; j < word.length(); j++) {
                mask |= 1 << (word.charAt(j) - 'a');
            }
            masks[i] = mask;
        }
        
        int maxProduct = 0;
        
        for (int i = 0; i < words.length - 1; i++) {
            for (int j = i + 1; j < words.length; j++) {
                int curMaxProduct = words[i].length() * words[j].length();
                if (curMaxProduct <= maxProduct) {
                    break; //prunning
                }
                if ((masks[i] & masks[j]) == 0) {
                    maxProduct = curMaxProduct;
                }
            }
        }
        return maxProduct;
        
    }
}
comments powered by Disqus