10.3Maximum Product of Word Lengths二进制特性题目描述给定多个字母串求其中任意两个字母串的长度乘积的最大值且这两个字母串不能含有相同字母。输入输出样例Input [a, ab, abc,d, cd, bcd, abcd ]Output4#include iostream #include vector #include unordered_map #include string using namespace std; int maxProduct(vectorstring words) { unordered_mapint, int hash; int ans 0; for (const string word : words) { int mask 0; int size word.size(); // 生成字母位掩码 a-z 对应 0-25 位 for (char c : word) { mask | 1 (c - a); } // 保留当前掩码对应的最大长度 hash[mask] max(hash[mask], size); // C11 遍历 unordered_map不使用结构化绑定 for (const auto pair : hash) { int h_mask pair.first; int h_len pair.second; // 无公共字母 if (!(mask h_mask)) { ans max(ans, size * h_len); } } } return ans; } int main() { vectorstring words { a, ab, abc, d, cd, bcd, abcd }; cout maxProduct(words) endl; return 0; }
Maximum Product of Word Lengths二进制特性--力扣101算法题解笔记
10.3Maximum Product of Word Lengths二进制特性题目描述给定多个字母串求其中任意两个字母串的长度乘积的最大值且这两个字母串不能含有相同字母。输入输出样例Input [a, ab, abc,d, cd, bcd, abcd ]Output4#include iostream #include vector #include unordered_map #include string using namespace std; int maxProduct(vectorstring words) { unordered_mapint, int hash; int ans 0; for (const string word : words) { int mask 0; int size word.size(); // 生成字母位掩码 a-z 对应 0-25 位 for (char c : word) { mask | 1 (c - a); } // 保留当前掩码对应的最大长度 hash[mask] max(hash[mask], size); // C11 遍历 unordered_map不使用结构化绑定 for (const auto pair : hash) { int h_mask pair.first; int h_len pair.second; // 无公共字母 if (!(mask h_mask)) { ans max(ans, size * h_len); } } } return ans; } int main() { vectorstring words { a, ab, abc, d, cd, bcd, abcd }; cout maxProduct(words) endl; return 0; }