Maximum Product of Word Lengths解题报告

Description:

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.

Link:

https://leetcode.com/problems/maximum-product-of-word-lengths/description/

解题方法:

假设我们有n个单词,总共有N个字符。
因为没有找到一种方法可以使有相同字母的单词共享一个key的方法,所以这道题是O(n^2)级别的算法。
因为int有32位,如果把26个字母转化为int上每一个位的0或1。我们可以用根据出现字母的组合来定义一个key并且用int储存这个组合。

Tips:

string::size()返回的是size_type类型的值,所以在使用Max函数的时候要注意转换为int。

Time Complexity:

O(max(N, n^2))

完整代码:

int maxProduct(vector<string>& words) 
    { 
        unordered_map<int, int> hash;
        for(string str: words)
        {
            int mask = 0;
            for(char ch: str)
            {
                mask |= (1 << (ch - 'a'));
            }
            hash[mask] = max(hash[mask], (int)str.size());   //different words may have same mask, so we need to save the max value
        }
        int maxPrud = 0;
        for(auto a: hash)
        {
            for(auto b: hash)
            {
                if(!(a.first & b.first))    //a and b have different masks, which means a and b don't share common letter
                    maxPrud = max(a.second * b.second, maxPrud);
            }
        }
        return maxPrud;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容