LeetCode--318. Maximum Product of Word Lengths

问题链接:https://leetcode.com/problems/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.

问题要求找到长度乘积最大的一对单词,并且这两个单词没有相同的字母。刚拿到这个问题时,开始想到的就是暴力方法,枚举单词对,检查是否有相同字符,如果没有就进行乘积的比较。但在Discuss里发现了基于位运算的十分漂亮的解法,利用了32位int的二进制表达也具有编码特性,int的二进制表达从右往左bit位(26个bit位对应26个小写字母)上的1代表某个字母存在于该单词中,然后问题就归结为一个&位运算,十分精巧,代码如下:

class Solution {
    public int maxProduct(String[] words) {
        
        int[] mapBit=new int[words.length];
        
        for(int i=0;i<words.length;i++)
        {
            for(int j=0;j<words[i].length();j++)
            {
                mapBit[i] =mapBit[i] | (1<< (words[i].charAt(j)-'a'));
            }
        }
        
        int ret=0;
        for(int i=0;i<words.length-1;i++)
        {
            for(int j=i;j<words.length;j++)
            {
                if((mapBit[i] & mapBit[j])==0)
                    ret=Math.max(ret,words[i].length()*words[j].length());
            }
        }
        
        return ret;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值