Maximum Product of Word Lengths

题目链接:
https://leetcode.com/problems...

public class Solution {
    public int maxProduct(String[] words) {
        // bit array to store the words
        // each word use bit represent: 1 << (c - 'a')
        int n = words.length;
        int[] nums = new int[n];
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < words[i].length(); j++) {
                nums[i] = nums[i] | (1 << words[i].charAt(j) - 'a');
            }
        }
        
        // check & == 0
        int max = 0;
        for(int i = 0; i < n; i++) {
            for(int j = i + 1; j < n; j++) {
                if((nums[i] & nums[j]) == 0) max = Math.max(max, words[i].length() * words[j].length());
            }
        }
        return max;
    }
}

除了用bit先处理之外,还可以用set保存所有不含某个字母的word,python这么写。参考这个博客:
http://bookshadow.com/weblog/...


lulouch13
13 声望6 粉丝

« 上一篇
H-Index & II