Leetcode - Maximum Product of Word Lengths

My code:

public class Solution {
    public int maxProduct(String[] words) {
        int max = 0;
        int len = words.length;
        int[] bits = new int[len];
        for (int i = 0; i < len; i++) {
            for (int j = 0; j < words[i].length(); j++) {
                bits[i] |= 1 << (words[i].charAt(j) - 'a');
            }
        }
        
        for (int i = 0; i < len; i++) {
            for (int j = i + 1; j < len; j++) {
                if ((bits[i] & bits[j]) == 0) {
                    max = Math.max(max, words[i].length() * words[j].length());
                }
            }
        }
        
        return max;
    }
}

reference:
https://discuss.leetcode.com/topic/35539/java-easy-version-to-understand

這道題目我一開始的做法就是申請一個
boolean[] dict = new boolean[26];

下面是我的代碼:
My code:

public class Solution {
    public int maxProduct(String[] words) {
        int max = 0;
        for (int i = 0; i < words.length; i++) {
            boolean[] dict = new boolean[26];
            for (int k = 0; k < words[i].length(); k++) {
                dict[words[i].charAt(k) - 'a'] = true;
            }
            
            for (int j = i + 1; j < words.length; j++) {
                if (words[j].length() <= max / words[i].length()) {
                    continue;
                }
                boolean doesIntersect = false;
                for (int k = 0; k < words[j].length(); k++) {
                    if (dict[words[j].charAt(k) - 'a']) {
                        doesIntersect = true;
                        break;
                    }
                }
                if (!doesIntersect) {
                    max = Math.max(max, words[i].length() * words[j].length());
                }
            }
        }
        
        return max;
    }
}

然后也盡量剪枝了。但還是很慢。
看了答案后,發現是用 Bit manipulation 做,真的很巧妙。

Anyway, Good luck, Richardo! -- 10/13/2016

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容