LeetCode刷题实战318:最大单词长度乘积
共 6422字,需浏览 13分钟
·
2021-07-13 18:51
Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.
示例
示例 1:
输入: ["abcw","baz","foo","bar","xtfn","abcdef"]
输出: 16
解释: 这两个单词为 "abcw", "xtfn"。
示例 2:
输入: ["a","ab","abc","d","cd","bcd","abcd"]
输出: 4
解释: 这两个单词为 "ab", "cd"。
示例 3:
输入: ["a","aa","aaa","aaaa"]
输出: 0
解释: 不存在这样的两个单词。
解题
class Solution {
public:
int maxProduct(vector<string>& words) {
int result = 0;
int wordsSize = words.size();
//対第一个字符串穷举
for (int nowIndex = 0; nowIndex < wordsSize; ++nowIndex){
//标记第一个字符串各个字符出现
map<char, bool> firstMap;
for (auto ch : words[nowIndex]){
firstMap[ch] = true;
}
//穷举第二个字符串
for (int afterIndex = nowIndex + 1; afterIndex < wordsSize; ++afterIndex){
int afterWordSize = words[afterIndex].size(), tempIndex = 0;
//判读第一个、第二个字符串是否存在相同的字符
for (; tempIndex < afterWordSize; ++tempIndex){
if (firstMap[words[afterIndex][tempIndex]]){
break;
}
}
//如果不存在相同的字符
if (afterWordSize == tempIndex){
result = max(int(afterWordSize * words[nowIndex].size()), result);//更新结果
}
}
}
return result;
}
};
class Solution {
public:
int maxProduct(vector<string>& words) {
int result = 0;
int wordsSize = words.size();
vector<int> wordToInt(wordsSize, 0);//wordToInt[i]表示words[i]按照字母分别占据以为得到的int数据
//対第一个字符串穷举
for (int nowIndex = 0; nowIndex < wordsSize; ++nowIndex){
//将第一个字符串按照字符占据位,计算为int
for (auto ch : words[nowIndex]){
wordToInt[nowIndex] |= (1 << (ch - 'a'));
}
//穷举第二个字符串
for (int afterIndex = 0; afterIndex < nowIndex; ++afterIndex){
//如果不存在相同的字符
if ((wordToInt[nowIndex] & wordToInt[afterIndex]) == 0){
result = max(result, int(words[nowIndex].size() * words[afterIndex].size()));
}
}
}
return result;
}
};