您的位置:首页 > 其它

318. Maximum Product of Word Lengths

2016-03-14 13:17 288 查看
//超时算法
class Solution {
public:
int maxProduct(vector<string>& words) {
// int num=words.size();
if(!words.size()) return 0;
int product=0;
bool flag1[26];
bool flag;
for(auto a=words.begin();a!=words.end();a++)
{
memset(flag1,0,26);
int len1=(*a).size();
for(int i=0;i<len1;i++)
{
if(!flag1[(*a)[i]-'a']) flag1[(*a)[i]-'a']=true;
}
for(auto b=a+1;b!=words.end();b++)
{
int len2=(*b).size();
flag=false;
for(int i=0;i<len2;i++)
{
if(flag1[(*b)[i]-'a']) break;
flag=true;
}
if(flag&&len2*len1>product) product=len2*len1;
}
}
}
};

//96ms
class Solution {
public:
int maxProduct(vector<string>& words) {
if(!words.size()) return 0;
int len=words.size();
int *flag=new int[len];
int *len_word=new int[len];
int product=0;

for(int j=0;j<len;j++ )
{
flag[j]=0;
len_word[j]=words[j].size();
for(int i=0;i<len_word[j];i++)
{
flag[j] |= 1<<(words[j][i]-'a');
}
}
for(int i=0;i<len;i++)
{
for(int j=i+1;j<len;j++)
{
if(!(flag[i]&flag[j]) && len_word[i]*len_word[j]>product) product=len_word[i]*len_word[j];
}
}
delete [] flag;
delete [] len_word;
return product;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: