Maximum Product of Word Lengths

来源:互联网 发布:鲸鱼死后爆炸知乎 编辑:程序博客网 时间:2024/04/30 03:39

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.


在一组字符串中选取两个长度乘积最大的,并且这两个字符串不能含有相同的字符。


首先要排除掉有相同字符的,不进行比较。将字符串转换成二进制,每个字幕对应一位,这样两个字符串的二进制数进行安位与,为0就说明没有相同的字母。

#include<iostream>#include<math.h>#include<vector>#include<string>using namespace std;class Solution{public:int maxProduct(vector<string>& words){int max=0;int n=words.size();if(n==0) return max;int nums[n];int T;for(int i=0;i<n;i++){nums[i]=0;for(int j=0;j<words[i].size();j++)nums[i] | =1<<((int)(words[i][j]-'a'));}for(int i=0;i<n-1;i++)for(int j=i+1;j<n;j++){if((nums[i]&nums[j])==0){int T=words[i].size()*words[j].size();max=max>T?max:T;}}return max;}};int main(){vector<string> words;string m;Solution maxPro;while(cin>>m){words.push_back(m);}cout<<maxPro.maxProduct(words);//cout<<"m";return 0;}


0 0