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

318. Maximum Product of Word Lengths

2019-11-06 07:53:27
字体:
来源:转载
供稿:网友

暴力求解,超时。。。苦笑。。。

class Solution {public: bool hasCommon(string a,string b) { sort(a.begin(),a.end()); sort(b.begin(),b.end()); int indexA=0; int indexB=0; while(indexA<a.size()&&indexB<b.size()) { if(a[indexA]==b[indexB]) return true; else if(a[indexA]>b[indexB]) indexB++; else indexA++; } return false; } int maxPRoduct(vector<string>& Words) { //return hasCommon("asdf","ghjkkl"); int max=0; for(int i=0;i<words.size();i++) { for(int j=i;j<words.size();j++) { if(hasCommon(words[i],words[j])==false) { if(max<(words[i].length())*(words[j].length())) max=(words[i].length())*(words[j].length()); } } } return max; }};

看了参考答案,发现它也是暴力求解的,不过在比较两个字符的过程中,采用了更加高级的bit比较的方法,大大节省了比较的时间复杂度。并且存储每一个temp对应的最大的length。 值得借鉴:利用bit的方法,比较两字符之间是否有重复字符。

class Solution {public: int maxProduct(vector<string>& words) { map<int,int> maxLen; for(int i=0;i<words.size();i++) { int temp=0; for(int j=0;j<words[i].size();j++) temp=temp|(1<<(words[i][j]-'a')); if(maxLen[temp]<words[i].size()) maxLen[temp]=words[i].size(); } int max=0; for(map<int,int>::iterator it1=maxLen.begin();it1!=maxLen.end();it1++) { for(map<int,int>::iterator it2=maxLen.begin();it2!=maxLen.end();it2++) { if(((it1->first)&(it2->first))==0) { if(max<(it1->second)*(it2->second)) max=(it1->second)*(it2->second); } } } return max; }};
上一篇:学习-Git(1)

下一篇:并查集

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表