LeetCode 318. Maximum Product of Word Lengths

本文探讨如何通过位操作来检测两个仅包含小写字母'a'-'z'的单词是否共用字母,通过比较两个单词对应的位表示,若无共用字母,则位与运算结果为0。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The tough part here is on how to detect  whether two words sharing common letters.

As indicate in the question, each word only contains lower case letters 'a' - 'z', we can actually correlate this problem with "in a given string, detect whether there is any duplicates". The difference here is to detect duplicates between two strings.

 thus, we can use  idea that  if two words contains no common letters, their & operation result should be 0. 

Example:

    ['"abc", "de"] -- > [0x111, 0x11000], thus, 0x111 & 0x11000 -> 0.


// I originally thought about to use unordered_map<int, int> to store the getBits and string size. However, it is easy to make problems.
int getBits(string& str) {
    int bits = 0;
    for(char c : str) {
        bits |= (1 << (c - 'a'));
    }
    return bits;
}
int maxProduct(vector<string>& words) {
    int result= 0;
    int size = words.size();
    vector<int> m(size, 0);
    vector<int> n(size, 0);
    for(int i = 0; i < size; ++i) {
        m[i] = getBits(words[i]);
        n[i] = words[i].size();
    }
    // seems like there is no better method to get the max.....
    for(int i = 0;  i < size; ++i) {
        for(int j = i + 1; j < size; ++j) {
            // there is no common letters.
            if((m[i] & m[j]) == 0) { 
                result = max(n[i] * n[j], result);
            }
        }
    }
    return result;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值