Question

Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.

Example 1:

Input: ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16
Explanation: The two words can be "abcw", "xtfn".

Example 2:

Input: ["a","ab","abc","d","cd","bcd","abcd"]
Output: 4
Explanation: The two words can be "ab", "cd".

Example 3:

Input: ["a","aa","aaa","aaaa"]
Output: 0
Explanation: No such pair of words.

Thinking:

  • Method 1:Brutal force
class Solution {
    public int maxProduct(String[] words) {
        int res = 0;
        int len = words.length;
        int[][] map = new int[len][26];
        for(int i = 0; i < len; i++){
            char[] arr = words[i].toCharArray();
            for(int j = 0; j < arr.length; j++){
                int c = arr[j] - 'a';
                map[i][c]++;
            }
        }
        for(int i = 0; i < words.length - 1; i++){
            int[] arr1 = map[i];
            LABEL:
            for(int j = i + 1; j < words.length; j++){
                int[] arr2 = map[j];
                for(int k = 0; k < 26; k++){
                    if(arr1[k] != 0 && arr2[k] != 0)
                        continue LABEL;
                }
                res = Math.max(res, words[i].length() * words[j].length());
            }
        }
        return res;
    }
}
  • Method 2:
    • 用int型的数的后26位表示字母是否出现。
    • 两个数相与(&)等于0就说明这两个单次未出现重复。
class Solution {
    public int maxProduct(String[] words) {
        int len = words.length;
        int[] mask = new int[len];
        int res = 0;
        for(int i = 0; i < len; i++){
            char[] arr = words[i].toCharArray();
            for(int j = 0; j < arr.length; j++){
                int c = arr[j] - 'a';
                mask[i] |= 1 << c;
            }
        }
        for(int i = 0; i < len - 1; i++){
            for(int j = i + 1; j < len; j++){
                if((mask[i] & mask[j]) == 0)
                    res = Math.max(res, words[i].length() * words[j].length());
            }
        }
        return res;
    }
}