318. Maximum Product of Word Lengths
My SubmissionsTotal Accepted: 19855 Total Submissions: 50022 Difficulty: Medium
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.
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
题解:
find the maximum value of
length(word[i]) * length(word[j])
where the two words do not share common letters.重点在于 判断 有没有重复的字母
由于只有小写字母(26个),所以用 状压,位运算 (与)即可
1 class Solution { 2 public: 3 int maxProduct(vector<string>& words) { 4 int n = words.size(); 5 vector <int> len; 6 vector <int> contain; 7 int i,j; 8 int l; 9 for(i = 0;i < n;i++){ 10 l = words[i].length(); 11 len.push_back(l); 12 int tmp = 0; 13 for(j = 0;j < l;j++){ 14 int x = words[i][j] - 'a'; 15 tmp |= (1 << x); 16 } 17 contain.push_back(tmp); 18 } 19 int re = 0; 20 for(i = 0;i < n;i++){ 21 for(j = i + 1;j < n;j++){ 22 if(contain[i] & contain[j]){ 23 continue; 24 } 25 re = max(re,len[i] * len[j]); 26 } 27 } 28 return re; 29 } 30 };