其实算是暴力计算了,踩着线过了,如果数据范围设大一点应该就过不了
cpp/c++实现:
#include<vector>
#include<string>
#include<iostream>
#include<map>
using namespace std;
class Solution {
public:
int maxProduct(vector<string>& words) {
int ans = 0;
// 单词中的每个单词长度
vector<int> orlen{};
for (auto& word: words){
orlen.push_back(word.length());
}
// 对words中的单词,跟它没有相同字母的最大长度的index
map<int,int> lenmax;
for (int i=0; i<words.size(); i++){
int maxlen = 0;
lenmax[i] = maxlen; // 初始化
for (int j=i+1; j<words.size(); j++){
string word = words[j];
bool find = false;
for (char achar:word){
size_t pos = words[i].find(achar);
if (pos<1000){
find = true; // 在里面有它的字母
break;
}
}
if (find==true){
continue;
}
if (word.length()>maxlen){
// cout<<"word's length:"<<word.length()<<endl;
maxlen = word.length();
lenmax[i] = maxlen;
}
}
}
// for (auto iter = lenmax.begin(); iter!=lenmax.end(); iter++){
// cout<<iter->first<<": "<<iter->second<<endl;
// }
for (int i=0; i<words.size(); i++){
int tmp = orlen[i]*lenmax[i];
if (tmp>ans){
ans = tmp;
}
}
return ans;
}
};
int main(){
Solution s;
vector<string> words {"a","aa","aaa","aaaa"};
int ans = s.maxProduct(words);
cout<<ans<<endl;
}