318. Maximum Product of Word Lengths

Posted ZHOU YANG

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了318. 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.

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

思路:利用bitmap的方法,将字符串转换为数字。对于字符串中的每个字符ch,转换为1<<(ch-‘a‘).只要两个字符串转换之后的数字进行&操作结果为0,说明这两个字符串没有相同的字符。就可以求这两个字符串的长度的乘积,和最终要返回的值ret比较,保证ret一直是最大的。为了简化步骤,可以首先将字符串按照长度进行排序,长度较长的字符串排在前面。这样,在内部循环之中,只要满足条件可以计算乘积,内部循环就马上终止,因为后续就算计算出了乘积也一定比当前计算的乘积值要小。同样的,在外部循环之中,如果ret>=(words[i].length()*words[i].length()),那么直接终止循环,因为后面计算出的乘积一定比ret要小。

class Solution {
private:
    static bool cmp(string a,string b){
        return a.length()>b.length();
    }
    
public:
    int maxProduct(vector<string>& words) {
        int size=words.size();
        sort(words.begin(),words.end(),cmp);
        vector<int> numbers;
        for(string word:words){
            int num=0;
            for(char ch:word){
                num|=1<<(ch-a);
            }
            numbers.push_back(num);
        }
        int ret=0;
        for(int i=0;i<size-1;i++){
            if(words[i].length()*words[i].length()<=ret)
                break;
            for(int j=i+1;j<size;j++){
                int product=(words[i].length()*words[j].length());
                if((numbers[i]&numbers[j])==0){
                    ret= max(product,ret);
                    break;
                }
            }
        }
        
        return ret;
        
    }
};

 

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

318. Maximum Product of Word Lengths

318. Maximum Product of Word Lengths

318. Maximum Product of Word Lengths

318. Maximum Product of Word Lengths

318. Maximum Product of Word Lengths

LeetCode 318. Maximum Product of Word Lengths