Leetcode 318. 最大单词长度乘积
题目
给定一个字符串数组 words,找到 length(word[i]) * length(word[j]) 的最大值,并且这两个单词不含有公共字母。你可以认为每个单词只包含小写字母。如果不存在这样的两个单词,返回 0。
测试样例
示例 1:
输入: ["abcw","baz","foo","bar","xtfn","abcdef"]
输出: 16
解释: 这两个单词为 "abcw", "xtfn"。
示例 2:
输入: ["a","ab","abc","d","cd","bcd","abcd"]
输出: 4
解释: 这两个单词为 "ab", "cd"。
示例 3:
输入: ["a","aa","aaa","aaaa"]
输出: 0
解释: 不存在这样的两个单词。
题解
是否具有字母转化为位运算
用一个32位数,每一位分别对应着某个字母,如果单词中有字母,则编码时对应位为1。因此,我们先对每个单词进行编码,然后再遍历,符合条件的两个单词他们的编码相与应该为0。详细过程见代码
代码
int str2int(string& str){
int len = str.length();
int res = 0;
for(int i=0; i<len; i++)
res |= 1 << (str[i]-'a');
return res;
}
int maxProduct(vector<string>& words) {
int n = words.size();
vector<int> wordsInt;
for(int i=0; i<n; i++)
wordsInt.push_back(str2int(words[i]));
int ans=0;
for(int i=0; i<n; i++){
for(int j=i+1; j<n; j++){
if(!(wordsInt[i]&wordsInt[j]) && ans < words[i].length()*words[j].length())
ans = words[i].length()*words[j].length();
}
}
return ans;
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-of-word-lengths
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。