首页 > 学院 > 开发设计 > 正文

318. Maximum Product of Word Lengths

2019-11-08 03:24:10
字体:
来源:转载
供稿:网友

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,说明没有共同的字母咯。

26和32这个梗,确实要能接住,说白了就是看能不能把string的比较问题和int的操作联系在一起。想起之前说过的话,事物间都天然存在各种联系,就看自己有没有火眼金睛能一眼看破看穿。这也是本事,得练!但归根到底,是从心里接受这个观念,并长期使用这个观念!另一个可以说的地方是,再次把一个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; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表