问题描述:
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.
示例:
Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
Return 16
The two words can be "abcw", "xtfn"
.
Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"]
Return 4
The two words can be "ab", "cd"
.
Given ["a", "aa", "aaa", "aaaa"]
Return 0
No such pair of words.
问题分析:
将每个字串中的字母都映射到二进制位上,所有出现相同字母的字串,他们对应的二进制数按位与所得的值均不为0,利用这个性质即可求解问题。
过程详见代码:
class Solution {
public:
int maxProduct(vector<string>& words) {
int res = 0;
vector<int> byte(words.size());
for (int i = 0; i < words.size(); i++)
{
int val = 0;
for (int j = 0; j < words[i].size(); j++)
{
val |= (1 << (words[i][j] - 'a'));
}
byte[i] = val;
}
for (int i = 0; i < words.size(); i++)
{
for (int j = i + 1; j < words.size(); j++)
{
if ((byte[i] & byte[j]) == 0)
{
res = max(res, (int)(words[i].length() * words[j].length()));
}
}
}
return res;
}
};