# 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.

``````class Solution {
public:
int maxProduct(vector<string>& words) {
int res = 0;
for (int i = 0; i < words.size(); ++i) {
for (char c : words[i]) {
mask[i] |= 1 << (c - 'a');
}
for (int j = 0; j < i; ++j) {
res = max(res, int(words[i].size() * words[j].size()));
}
}
}
return res;
}
};
``````

``````class Solution {
public:
int maxProduct(vector<string>& words) {
int res = 0;
unordered_map<int, int> m;
for (string word : words) {
for (char c : word) {
mask |= 1 << (c - 'a');
}
for (auto a : m) {
res = max(res, (int)word.size() * a.second);
}
}
}
return res;
}
};
``````

https://leetcode.com/discuss/74580/bit-shorter-c

https://leetcode.com/discuss/75034/clear-and-easily-understanding

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation