标签:href https 示例 ret strong 位运算 数组 amp 著作权
给定一个字符串数组?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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1.或运算记录字母是否出现
int 32位, 小写字母26位,1代表出现,0代表未出现
1 << x 表示1左移x位,又或者是2的x次方
for (int i = 0; i < n; i++){
for (char ch : words[i]){
a[i] |= 1 << (ch - ‘a‘);
}
}
2.与运算判断两单词是否有重复字母
a[i] & a[j] 若不为0,则说明有重复字母
!(a[i] & a[j])
class Solution {
public:
int maxProduct(vector<string>& words) {
int n = words.size();
vector <int> a(n,0);
for (int i = 0; i < n; i++){
for (char ch : words[i]){
a[i] |= 1 << (ch - ‘a‘);
}
}
int ans = 0;
for (int i = 0; i < n - 1; i++){
for (int j = i + 1; j < n; j++){
if (!(a[i] & a[j])){
ans = max(ans, (int)words[i].size() * (int)words[j].size());
}
}
}
return ans;
}
};
标签:href https 示例 ret strong 位运算 数组 amp 著作权
原文地址:https://www.cnblogs.com/xgbt/p/13200338.html