Tuesday, December 29, 2015

[LeetCode] Maximum Product of Word Lengths

Reference: https://leetcode.com/discuss/74589/32ms-java-ac-solution
public class Solution {
    public int maxProduct(String[] words) {
        if (words == null || words.length <= 1) return 0;
        Arrays.sort(words, new Comparator<String>() {
            @Override
            public int compare(String str1, String str2) {
                return str2.length() - str1.length();
            }
        });
        int[] wordHash = hashWords(words);
        int maximumProduct = 0;
        int left = 0, right = words.length - 1;
        while (left < right) {
            for (int i = left + 1; i <= right; i++) {
                if ((wordHash[left]&wordHash[i]) == 0) {
                    maximumProduct = Math.max(maximumProduct, words[left].length() * words[i].length());
                    right = i - 1;
                    break;
                }
            }
            left++;
        }
        return maximumProduct;
    }
   
    private int[] hashWords(String[] words) {
        int[] hash = new int[words.length];
        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            for (int j = 0; j < word.length(); j++) {
                hash[i] |= (1 << (word.charAt(j) - 'a'));
            }
        }
        return hash;
    }
}

No comments:

Post a Comment