LeetcodeMaximum Product of Word Lengths

Posted wuezs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetcodeMaximum Product of Word Lengths相关的知识,希望对你有一定的参考价值。

题目链接:https://leetcode.com/problems/maximum-product-of-word-lengths/

题目:
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:
Given [“abcw”, “baz”, “foo”, “bar”, “xtfn”, “abcdef”]
Return 16
The two words can be “abcw”, “xtfn”.

Example 2:
Given [“a”, “ab”, “abc”, “d”, “cd”, “bcd”, “abcd”]
Return 4
The two words can be “ab”, “cd”.

Example 3:
Given [“a”, “aa”, “aaa”, “aaaa”]
Return 0
No such pair of words.

思路:
一个int装化为2进制是32位,利用其中的26位来表示一个单词是否出现了某个字母,在比较两个单词是否含有共同字母的时候就可以将两者的int数字相与,若结果为0,则有共同字母。

算法:

    public int maxProduct(String[] words) {
        int max = 0;
        int words_value[] = new int[words.length];
        for (int i = 0; i < words.length; i++) {
            for (int j = 0; j < words[i].length(); j++) {
                char c = words[i].charAt(j);
                words_value[i] = words_value[i] | (1 << (c - ‘a‘));// 把1左移多少位
            }
        }
        for (int i = 0; i < words.length; i++) {
            for (int j = i + 1; j < words.length; j++) {
                int product = 0;
                if ((words_value[i] & words_value[j]) == 0) {
                    product = words[i].length() * words[j].length();
                }
                max = Math.max(max, product);
            }
        }
        return max;
    }

以上是关于LeetcodeMaximum Product of Word Lengths的主要内容,如果未能解决你的问题,请参考以下文章

leetcodeMaximum Subarray (53)

Leetcode 238 Product of Array Except Self 时间O(n)和空间O解法

LuoguP5221 Product

android O 蓝牙设备默认名称更改

Project Euler P4 Largest palindrome product 题解

Maximum Product Subarray