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; }};新聞熱點
疑難解答