318. Maximum Product of Word Lengths

来源:互联网 发布:手机淘宝怎么找店铺 编辑:程序博客网 时间:2024/05/15 04:24

题目:单词长度的最大积

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.


题意:

给定一个字符串数组words,找到两个没有相同字母的单词的长度之积的最大值。可以假设每一个单词只包含有小写字母。如果没有两个单词存在,返回0;


思路一:

用了mask,因为题目中说都是小写字母,那么只有26位,一个整型数int有32位,我们可以用后26位来对应26个字母,若为1,说明该对应位置的字母出现过,那么每个单词的都可由一个int数字表示,两个单词没有共同字母的条件是这两个int数想与为0。

代码:C++版:128ms

class Solution {public:    int maxProduct(vector<string>& words) {        int res = 0;        vector<int> mask(words.size(), 0); //使用int表示每个单词,存储在mask数组中        for (int i=0; i<words.size(); ++i) {            for (char c : words[i]) { //将每个单词处理为一个整数                mask[i] |= 1 << (c - 'a'); //26个字母,使用int中的26位表示            }            for (int j=0; j<i; ++j) { //将轮训到的该单词与之前所有的单词进行对比判断                if (!(mask[i] & mask[j])) { //不包含相同字母时                    res = max(res, int(words[i].size() * words[j].size())); //取更大值                }            }        }        return res;    }};

思路二:

另一种写法,借助哈希表,映射每个mask的值和其单词的长度,每算出一个单词的mask,遍历哈希表里的值,如果和其中的mask值相与为0,则将当前单词的长度和哈希表中存的单词长度相乘并更新结果。

代码:C++版:132ms

class Solution {public:    int maxProduct(vector<string>& words) {        int res = 0;        unordered_map<int, int> map;        for (string word : words) {            int mask = 0;            for (char c : word) { //同样将单词转换为整数                mask |= 1 << (c - 'a');            }            map[mask] = max(map[mask], int(word.size())); //建立整数与单词长度的映射关系            for (auto m : map) {                if (!(mask & m.first)) {                    res = max(res, (int)word.size() * m.second);                }            }        }        return res;    }};


0 0