给你一个字符串数组 words ,找出并返回 length(words[i]) * length(words[j]) 的最大值,并且这两个单词不含有公共字母。如果不存在这样的两个单词,返回 0

示例 1:

输入:words = ["abcw","baz","foo","bar","xtfn","abcdef"] 输出:16 解释:这两个单词为 "abcw", "xtfn"

示例 2:

输入:words = ["a","ab","abc","d","cd","bcd","abcd"] 输出:4 解释:这两个单词为 "ab", "cd"

示例 3:

输入:words = ["a","aa","aaa","aaaa"] 输出:0 解释:不存在这样的两个单词。

提示:

  • 2 <= words.length <= 1000
  • 1 <= words[i].length <= 1000
  • words[i] 仅包含小写字母

代码实现

class Solution {
public:
    int ans = 0;
    int maxProduct(vector<string>& words){
        vector <int> bit;
        for (auto& s : words) {
            int x = 0;
            for (auto& ch : s)
                x |= (1 << (ch - 'a'));
            bit.push_back(x);
        }
        for (int i = 0; i < words.size(); ++i) 
            for (int j = i + 1; j < words.size(); ++j) 
                if (!(bit[i] & bit[j])) 
                    ans = max(ans, (int)words[i].length() * (int)words[j].length());
        return ans;
    }
}; 

0 条评论

发表回复

Avatar placeholder

您的电子邮箱地址不会被公开。 必填项已用*标注

友情链接:Ctips' blog, Colza’s blog

站点状态:Status