318. 最大单词长度乘积

给你一个字符串数组 words ,找出并返回 length(words[i]) * length(words[j]) 的最大值,并且这两个单词不含有公共字母。如果不存在这样的两个单词,返回 0 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-of-word-lengths
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

位运算

class Solution {

    private int toInt(String word) {
        int ans = 0;
        for (int i = 0; i < word.length(); ++i) {
            ans |= (1 << (word.charAt(i) - 'a'));
        }
        return ans;
    }

    public int maxProduct(String[] words) {
        if (words == null || words.length == 0) {
            return 0;
        }

        int[][] hash = new int[words.length][2];
        for (int i = 0; i < words.length; ++i) {
            hash[i][0] = words[i].length();
            hash[i][1] = toInt(words[i]);
        }

        int ans = 0;
        for (int i = 0; i < hash.length - 1; ++i) {
            for (int j = i + 1; j < hash.length; ++j) {
                if ((hash[i][1] & hash[j][1]) == 0) {
                    ans = Math.max(ans, hash[i][0] * hash[j][0]);
                }
            }
        }
        return ans;
    }
}

位运算优化

import java.util.HashMap;
import java.util.Map;

class Solution {

    private int toInt(String word) {
        int ans = 0;
        for (int i = 0; i < word.length(); ++i) {
            ans |= (1 << (word.charAt(i) - 'a'));
        }
        return ans;
    }

    public int maxProduct(String[] words) {
        if (words == null || words.length == 0) {
            return 0;
        }

        Map<Integer, Integer> maskLengthMap = new HashMap<>();
        for (int i = 0; i < words.length; ++i) {
            int mask = toInt(words[i]);
            maskLengthMap.put(mask, Math.max(words[i].length(), maskLengthMap.getOrDefault(mask, 0)));
        }

        int ans = 0;

        for (Map.Entry<Integer, Integer> maskEntry1 : maskLengthMap.entrySet()) {
            for (Map.Entry<Integer, Integer> maskEntry2 : maskLengthMap.entrySet()) {
                if ((maskEntry1.getKey() & maskEntry2.getKey()) == 0) {
                    ans = Math.max(ans, maskEntry1.getValue() * maskEntry2.getValue());
                }
            }
        }
        return ans;
    }
}
posted @ 2022-02-17 16:45  Tianyiya  阅读(31)  评论(0)    收藏  举报