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:
Given [“abcw”, “baz”, “foo”, “bar”, “xtfn”, “abcdef”]
Return 16
The two words can be “abcw”, “xtfn”.

Example 2:
Given [“a”, “ab”, “abc”, “d”, “cd”, “bcd”, “abcd”]
Return 4
The two words can be “ab”, “cd”.

Example 3:
Given [“a”, “aa”, “aaa”, “aaaa”]
Return 0
No such pair of words.

s思路:
1. 只有小写字母,说明啥?说明只有26种可能,比int的32路并行数据还小,也就是说,把每个数含有每个字母的情况用一个int就给完全表示了,然后就两两相与,如果相与等于0,说明没有共同的字母咯。

  1. 26和32这个梗,确实要能接住,说白了就是看能不能把string的比较问题和int的操作联系在一起。想起之前说过的话,事物间都天然存在各种联系,就看自己有没有火眼金睛能一眼看破看穿。这也是本事,得练!但归根到底,是从心里接受这个观念,并长期使用这个观念!
  2. 另一个可以说的地方是,再次把一个int看成一个容器,可以装进去32种并行的结果,所以int就不只是一个普通的数了,这就是看问题的角度了,怎么看能看到不同的用途!
class Solution {
public:
    int maxProduct(vector<string>& words) {
       //
       if(words.size()<=1) return 0;
       vector<int> res(words.size());
       for(int i=0;i<words.size();i++){
           for(char c:words[i]){
                res[i]=res[i]|(1<<(c-'a'));   
            }    
       }
       int mx=0;
       for(int i=0;i<words.size()-1;i++){
            for(int j=i+1;j<words.size();j++){
                if((res[i]&res[j])==0){
                    mx=max(mx,int(words[i].size()*words[j].size()));
                    //bug:size()的返回类型不是int,需要强制转换
                }   
            }   
       }
       return mx;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值