马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
题目描述:给定一个字符串数组 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
解释: 不存在这样的两个单词。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-of-word-lengths
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
int bitNumber(char ch) {
return (int)ch - (int)'a';
}
int maxProduct(vector<string>& words) {
int n = words.size();
vector<int> masks = vector<int>(n);
vector<int> lens = vector<int>(n);
//位运算
int bitmask = 0;
for (int i = 0; i < n; ++i) {
bitmask = 0;
for (char cha : words[i]) {
bitmask |= 1 << bitNumber(cha);
}
masks[i] = bitmask;
lens[i] = words[i].size();
}
int maxVal = 0;
for (int i = 0; i < n; ++i){
for (int j = i + 1; j < n; ++j){
if ((masks[i] & masks[j]) == 0){
maxVal = max(maxVal, lens[i] * lens[j]);
}
}
}
return maxVal;
}
};
参考链接:https://leetcode-cn.com/problems ... eng-ji-by-leetcode/ |