[leetcode]318. Maximum Product of Word Lengths
Analysis
要加油鸭。。。—— [每天刷题并不难。。。]
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.
因为所有单词都只包含小写字母,而int最大有32位,所以可以用其中的26位来存每个字母是否出现。如果一个一个字母的判断会超时,所以直接改为判断两个数的与运算是否为0.
Implement
class Solution {
public:
int maxProduct(vector<string>& words) {
int len = words.size();
int res = 0;
vector<int> mask(len, 0);
for(int i=0; i<len; i++){
for(auto c:words[i])
mask[i] |= 1<<(c-'a');
for(int j=0; j<i; j++){
if((mask[i]&mask[j]) == 0)
res = max(res, int(words[i].size()*words[j].size()));
}
}
return res;
}
};