leetcode 318. Maximum Product of Word Lengths(单词长度的最大积)

Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.

Example 1:

Input: words = [“abcw”,“baz”,“foo”,“bar”,“xtfn”,“abcdef”]
Output: 16
Explanation: The two words can be “abcw”, “xtfn”.
Example 2:

Input: words = [“a”,“ab”,“abc”,“d”,“cd”,“bcd”,“abcd”]
Output: 4
Explanation: The two words can be “ab”, “cd”.

string数组中找出两个单词,使它们长度的积最大。
但是这两个单词不能包含相同的字母。

思路:
如果没有不能包含相同字母这条限制,
做法应该是找出长度最大的前2个单词,把它们的长度相乘。

所以现在任务转变为如何判断两个单词是否含有相同的字母。
每次都一个一个比较太麻烦。

注意到字母一共就只有26个,如果能用26个bit位表示每个单词是否含有这26个字母,
比较的时候bit与一下,结果是0就说明这2个单词没有相同的字母。

所以第一步,用bit位表示每个单词是否含有26个字母,
第2步,bit与的结果为0时,取长度积的最大值。

    public int maxProduct(String[] words) {
        int n = words.length;
        int[] masks = new int[n];
        int res = 0;
        
        for(int i = 0; i < n; i ++) {
            for(int k = 0; k < words[i].length(); k++) {
                masks[i] |= (1 << words[i].charAt(k) - 'a');
            }
        }
        
        for(int i = 0; i < n-1; i++) {
            for(int j = i+1; j < n; j++) {
                if((masks[i] & masks[j]) == 0) {
                    res = Math.max(res, words[i].length() * words[j].length());
                }
            }
        }
        return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值