11-17 Leetcode318. 最大单词长度乘积

2021/11/17 23:14:07

本文主要是介绍11-17 Leetcode318. 最大单词长度乘积,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Leetcode318. 最大单词长度乘积

思路:位运算

如何判断不同单词字母重复?题目的提示是只用小写字母,保证所有的字母最多只有26个,使用 i n t int int前26位保存每一个字母是否出现过,使用 h a s h hash hash存所有单词对应的特征,两次循环遍历哈希表

class Solution {
public:
    int maxProduct(vector<string>& words) {
        int n = words.size();
        unordered_map<int, string> hash;
        for (auto& str : words) {
            int m = str.size(), t = 0;
            for (auto& c : str) {
                int u = c - 'a';
                t |= (1 << u);
            }
            if (!hash.count(t) || hash[t].size() < m) hash[t] = str;
        }
        int res = 0;
        for (auto& [n, str1] : hash)
            for (auto &[m, str2]: hash)
                if ((n & m) == 0) {
                    int x = str1.size() * str2.size();
                    if (x > res) {
                        res = x;
                    }
                }   
        return res;
    }
};


这篇关于11-17 Leetcode318. 最大单词长度乘积的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程