318. Maximum Product of Word Lengths

本文介绍了一种算法,用于解决给定字符串数组中寻找两个不包含相同字母的单词,以获得它们长度的最大乘积。通过使用位运算,该算法能够高效地检查两单词是否包含重复字符。

Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.

Example 1:

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

Input: ["a","ab","abc","d","cd","bcd","abcd"]
Output: 4 
Explanation: The two words can be "ab", "cd".
Example 3:

Input: ["a","aa","aaa","aaaa"]
Output: 0 
Explanation: No such pair of words.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-of-word-lengths
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

判断是否有不同数字时,可以采用bit来记录每一个位。再取&,如果有相同的,那么&的结果肯定不是0;

class Solution {
    public int maxProduct(String[] words) {
        int ans = 0;
        for (int i = 0; i < words.length; i++) {
            for (int j = i + 1; j < words.length; j++) {
                if (isDiff(words[i], words[j])) {
                    ans = Math.max(ans, words[i].length() * words[j].length() );
                }
            }
        }
        return ans;
    }
    public boolean isDiff(String str1, String str2){
        int num1 = 0;
        int num2 = 0;
        for (char a: str1.toCharArray()) {
            num1 = num1 | 1 << (a - '0');
        }
        for (char a: str2.toCharArray()) {
            num2 = num2 | 1 << (a - '0');
        }
        int and = num1 & num2;
        return and == 0;
    }
}

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值