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.

 
public class Solution {
    public int maxProduct(String[] words) {
        if (words == null || words.length <= 1) {
            return 0; 
        }
        //Use bit manipulation to record what char is included in a word 
        //The representation of each word is a number.
        int[] processedWords = new int[words.length];
        //if a certain char exist, the corresponding bit is set to 1
        for (int i = 0;  i < words.length; i++) {
            for (int j = 0; j < words[i].length(); j++) {
                //the corresponding numerical number of the given char
                int num = 1 << words[i].charAt(j) - 'a'; 
                processedWords[i] = processedWords[i] | num; 
            }
        }
        
        //checking & calculation 
        int maxProduct = 0; 
        for (int i = 0; i < words.length; i++) {
            for (int j = i+1; j < words.length; j++) {
                //Compare two words 
                if (((processedWords[i] & processedWords[j]) == 0) 
                    && words[i].length()*words[j].length() > maxProduct) {
                      maxProduct = words[i].length()*words[j].length();   
                }
            }
        }
        return maxProduct;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s