leetcode@ [318] Maximum Product of Word Lengths (Bit Manipulations)

https://leetcode.com/problems/maximum-product-of-word-lengths/

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.

class Solution {
public: void strToBits(vector<int>& bits, vector<string>& words) {
for(int i=; i<words.size(); ++i) {
int tmp = ;
for(int j=; j<words[i].size(); ++j) {
int offset = words[i][j] - 'a';
tmp = (tmp | ( << offset));
}
bits[i] = tmp;
}
} int maxProduct(vector<string>& words) {
int n = words.size();
if(n < ) return ; vector<int> bits(n, );
strToBits(bits, words); int res = ;
for(int i=; i<n; ++i) {
for(int j=i+; j<n; ++j) {
int len1 = words[i].length(), len2 = words[j].length();
if((bits[i] & bits[j]) == ) {
res = max(res, len1 * len2);
}
}
} return res;
}
};
上一篇:App自动化测试工具总结


下一篇:5本自然语言处理书单-附pdf