码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 318. Maximum Product of Word Lengths

时间:2018-06-26 11:12:04      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:将不   space   字符   hat   tor   amp   sha   存在   long   

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:

Input: ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16 
Explanation: The two words can be "abcw", "xtfn".

Example 2:

Input: ["a","ab","abc","d","cd","bcd","abcd"]
Output: 4 
Explanation: The two words can be "ab", "cd".

Example 3:

Input: ["a","aa","aaa","aaaa"]
Output: 0 
Explanation: No such pair of words.

 

思路:

1.需要找到有效的方法来比较字符串中是否含有相同的元素。 (bitmask)

2.找到这种方法之后,直接遍历整个数组找最大的乘积就得出解了。(brute force)

Code:

 1 #include <vector>
 2 #include <string>
 3 using namespace std;
 4 int maxProduct(vector<string>& words) {
 5     int res = 0, n = words.size();
 6     vector<int> charBits(n, 0);
 7     for (int i = 0; i < n; i++) {
 8         charBits[i] = 0;
 9         for (int j = 0; j < words[i].size(); j++) {
10             charBits[i] |= 1 << (words[i][j] - ‘a‘);
11         }
12     }
13 
14     for (int i = 0; i < n; i++) {
15         for (int j = 0; j < n; j++) {
16             if ((charBits[i] & charBits[j]) == 0) {
17                 int product = words[i].size() * words[j].size();
18                 if (res < product) {
19                     res = product;
20                 }
21             }
22         }
23     }
24     return res;
25 }

详细解释:

Part1:

第10行代码:

//bitmask: bit operation,move "0x0001" left "(words[i][j] - ‘a‘)" bits; this way we can store different characters in charBits[i]
charBits[i] |= 1 << (words[i][j] - a);

从‘a‘到‘z‘一共有26个字母,一个int变量有32bit,每个字母与‘a‘相减得到的值(即0x0001需要左移的位置)不会超出int变量的范围。

通过将0x0001(即1)左移 “ words[i][j] - ‘a‘ ”位,我们将字母words[i][j]的信息存储在了位操作后的int数字上。(注意:即使存在重复的字母,也不会有影响。因为我们要存储的不是字符串的全部信息,仅仅是单词中所有不同字母的信息)

然后再通过 “|=”操作,将单词words[i]的j位置的字母words[i][j]存到变量charBits[i](即bitmask)中。

遍历整个单词,即可得到整个字符串的bitmask:charBits[i]。

遍历完整个words之后,我们就得到了每个单词words[i]的bitmask。

Part2:

之后在第16行代码中:

           if ((charBits[i] & charBits[j]) == 0) {

将不同单词words[i]和words[j]的bitmask(charBits[i]和charBits[j]),作&运算,只要不等于0,就说明两个单词有相同的字母。

一旦(charBits[i] & charBits[j]) == 0,则说明两个单词没有任何相同的字母。

 


 

延伸:

1.题设中的条件是只有小写字母,如果有大写字母怎么办?

答:用long或者bit[64]来存储字母的信息。

char c = words[i][j]
if (islower(c) {
    charBits[i] |= (long)1 << ( c - a);
} else {
    charBits[i] |= (long)1 << (( c - A)+32);
}

 

LeetCode 318. Maximum Product of Word Lengths

标签:将不   space   字符   hat   tor   amp   sha   存在   long   

原文地址:https://www.cnblogs.com/wolfpack/p/9226955.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!