318. Maximum Product of Word Lengths

来源:互联网 发布:python股票交易策略 编辑:程序博客网 时间:2024/06/07 00:39

Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.

Example 1:

Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
Return 16
The two words can be "abcw", "xtfn".

Example 2:

Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"]
Return 4
The two words can be "ab", "cd".

Example 3:

Given ["a", "aa", "aaa", "aaaa"]
Return 0

No such pair of words.

题意:给出一串字符串,如果两个字符串没有重复的字母,则两个字符串可以计算乘积,返回可能得到的最大的乘积。

思路:重点在于两个字符串有没有重复的字母。用一个int型的数,每位表示一个字母的有无,则26个位就可以表示对应26个字母的有无。

class Solution {public:int maxProduct(vector<string>& words) {const int size = words.size();if (size < 2)return 0;vector<int> flag(size, 0);for (int i = 0; i < size; i++){string s = words[i];for (int j = 0; j < s.size(); j++){flag[i] |= 1 << (s[j] - 'a');}}int res = 0;for (int i = 0; i < size; i++){for (int j = i; j < size; j++){if ((flag[i] & flag[j]) == 0)res = max(res, (int)(words[i].size()*words[j].size()));}}return res;}};







0 0
原创粉丝点击