[Leetcode] 第318题 最大单词长度乘积

 

1、题目描述数组

给定一个字符串数组 words,找到 length(word[i]) * length(word[j]) 的最大值,而且这两个单词不含有公共字母。你能够认为每一个单词只包含小写字母。若是不存在这样的两个单词,返回 0。spa

示例 1:code

输入: 
输出: 。["abcw","baz","foo","bar","xtfn","abcdef"]16 
解释: 这两个单词为"abcw", "xtfn"

示例 2:blog

输入: 
输出: 这两个单词为 。["a","ab","abc","d","cd","bcd","abcd"]4 
解释:"ab", "cd"

示例 3:字符串

输入: 
输出: ["a","aa","aaa","aaaa"]0 
解释: 不存在这样的两个单词。

2、题目分析string

1)这个问题的关键在于判断两个单词是否有重合的部分,要把全部单词两两组合一遍时间复杂度是n*n
2)因此判断部分应该尽可能用常数时间
3)采用位运算,把单词中字母出现的状况,映射成整数中位的状况,好比单词中含有'a',那么整数中从右向左第1位就是1,采用移位的方法
4)这个时间复杂度是n*sizeof(words[i]),每一位采用“或等于”计算
5)这样两个单词无交集就映射为bit_word作“与”运算为0it

3、代码io

 1 class Solution {
 2 public:
 3     int maxProduct(vector<string>& words) {
 4         int n = words.size();
 5         int res = 0;
 6         int i, j;
 7         vector<int>bit_word(n, 0);
 8         for (i = 0; i < n; ++i) {
 9             for (j = 0; j < words[i].size(); ++j) {
10                 bit_word[i] |= 1 << (words[i][j] - 'a');
11             }
12         }
13         for (i = 0; i < n; ++i) {
14             for (j = i + 1; j < n; ++j) {
15                 if (bit_word[i] & bit_word[j])continue;
16                 res = res < words[i].size()*words[j].size() ? words[i].size()*words[j].size() : res;
17             }
18         }
19         return res;
20     }
21 };
相关文章
相关标签/搜索