给你一个字符串数组 words ,找出并返回 length(words[i]) * length(words[j]) 的最大值,并且这两个单词不含有公共字母。如果不存在这样的两个单词,返回 0 。
示例 1:
输入:words = ["abcw","baz","foo","bar","xtfn","abcdef"]
输出:16
解释:这两个单词为 "abcw", "xtfn"。
示例 2:
输入:words = ["a","ab","abc","d","cd","bcd","abcd"]
输出:4
解释:这两个单词为 "ab", "cd"。
示例 3:
输入:words = ["a","aa","aaa","aaaa"]
输出:0
解释:不存在这样的两个单词。
提示:
- 2 <= words.length <= 1000
- 1 <= words[i].length <= 1000
- words[i] 仅包含小写字母
Code:
主要思路:这次是先去重然后再暴力枚举(把上一篇的emplace_back改为push_back即可)
class Solution {
public:
int maxProduct(vector<string>& words) {
int maxlen=0;
vector<int>lenvec;
for(int i=0;i<words.size();i++)
{
int len=words[i].length();
sort(words[i].begin(),words[i].end());
words[i].erase(unique(words[i].begin(),words[i].end()),words[i].end());
lenvec.push_back(len);
}
for(int i=0;i<words.size();i++)
{
for(int j=i+1;j<words.size();j++)
{
string str3=words[i]+words[j];
string str4=str3;
sort(str3.begin(),str3.end());
str3.erase(unique(str3.begin(),str3.end()),str3.end());
if(str3.length()==str4.length())
{
maxlen=max(maxlen,(lenvec[i]*lenvec[j]));
}
}
}
return maxlen;
}
};