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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容