【题解】Leetcode.318. 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.

题目大意:
给出一个只由小写字母组成的字符串数组,找出 字符串i的长度 × 字符串j的长度 最大的值,并且字符串i与字符串j中没有共同的字符。

思路:
首先为每个字符串建立一个包含字符的2进制表并计算长度,然后枚举所有字符串对,如果这对字符串的2进制表没有重合,就计算长度积并更新最大积。

实现:

int maxProduct(char** words, int wordsSize) {
    int *rec = (int*)malloc(sizeof(int)*wordsSize); // 2进制表
    int *len = (int*)malloc(sizeof(int)*wordsSize); // 长度表
    int rst = 0;
    char *p;
    for(int i = 0; i < wordsSize; i++){
        rec[i] = 0;
        for(p=words[i];*p;rec[i] |= 1<<(*p++-'a')); // 将对应位置1
        len[i] = p-words[i]; // 计算长度
    }

    for(int i = 0;i<wordsSize;i++)
        for(int j = i+1;j<wordsSize;j++)
            if(!(rec[i]&rec[j])) // 如果没有重叠位
                if(len[i] * len[j] > rst)
                    rst = len[i] * len[j];

    free(rec);
    free(len);
    return rst;
}

猜你喜欢

转载自blog.csdn.net/c_duoduo/article/details/52074741