Saturday, February 15, 2020

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:
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.
int maxProduct(vector<string>& words) {
        int ans = 0;
        int product = 1;
        
        if (words.size() == 0) {
            return ans;
        }
        
        for (int i = 0; i < words.size(); i++) {
            string word1 = words[i];
            unordered_map<char, int> mp;
            for (auto ch : word1) {
                mp[ch]++;
            }
            int len = word1.size();
            for (int j = i + 1; j < words.size(); j++) {
                if (!collide(words[j], mp)) {
                    int len2 = words[j].size();
                    ans = max(ans, len * len2);
                }
            }
        }
        return ans;
    }
    
    bool collide(string str, unordered_map<char, int>& mp) {
        for (auto ch : str) {
            if (mp.count(ch)) {
                return true;
            }
        }
        return false;
    }

Efficient way:
int maxProduct(vector<string>& words) {
        vector<int> nums;
        vector<int> lens;
        for (string s: words) {
            if (s.length() == 0) continue;
            int num = convertStringToBits(s);
            nums.push_back(num);
            lens.push_back(s.length());
        }
         
        int max_len = 0;
        for (int i = 0; i < nums.size(); i++) {
           for (int j = i+1; j < nums.size(); j++) {
               if ((nums[i] & nums[j]) == 0) {
                   int product = lens[i] * lens[j];
                   if (product > max_len) max_len = product;
               }
           }
        }
        return max_len;
    }
       
    int convertStringToBits(string s) {
        int result = 0;
        for (char cc : s) {
            int bit_index = cc-'a';
            result |= (1 << bit_index);
        }
        return result;
    }

No comments:

Post a Comment