代码改变世界

318_Maximum Product of Word Lengths

2016-01-12 16:12  FTD_W  阅读(488)  评论(0编辑  收藏  举报

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.

 

 

数组中每个元素是字符串

首先,我们把每个字符串转换为一个int型数。该int型数有26位,哪个字母出现过,该位为1(!!重复的字母只算一次)

其次,新得到的int型数组进行计算,两个int型数按位与(&)后为0则说明没有重复的字母

最后,得到最大值

 

public class Solution {
    public int MaxProduct(string[] words) {
        int[] intStore = new int[words.Length];
        int current = 0;
        int max = 0;
        
        for(int i = 0; i < words.Length; i++)
        {
            char[] ch = words[i].ToCharArray();
            current = 0;
            foreach(char c in ch.Distinct())
            {
                int pow = (int)c - (int)'a';
                current += (int)Math.Pow(2, pow);
            }
            intStore[i] = current;
        }
        
        for(int i = 0; i < intStore.Length; i++)
        {
            for(int j = i + 1; j < intStore.Length; j++)
            {  
                if( (int)(intStore[i] & intStore[j]) == 0)
                {
                    if(max < words[i].Length * words[j].Length) 
                    max = words[i].Length * words[j].Length;
                }
            }
        }
        
        return max;
    }
}