2016年2月4日 星期四

LEET code -- 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.

原本想暴力解  太是太蠢了

看了一下別人解法
把每個字行都利用1bit來代表  而一個int 有32bit可以表示  綽綽有餘
所以就可以比較了

要注意的是double pointer
是pointer of pointer
所以直接words[i][j]就好  因為外面是*words[] 再去每個malloc

    
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
int maxProduct(char** words, int wordsSize) {
    if(wordsSize==0 || words==NULL)return 0;
    int valuse[wordsSize];
    for(int i=0;i<wordsSize;i++){
        valuse[i]=0;
        int length=strlen(words[i]);
        for(int j =0;j<length;j++){
            valuse[i] |= 1<<(words[i][j]-'a');
        }
    }
    int max=0;
    for(int i=0;i<wordsSize;i++){
        for(int j=i+1;j<wordsSize;j++){
            if( (valuse[i] & valuse[j] )==0){
                int a=strlen(words[i]);
                int b=strlen(words[j]);
                max = max>(a*b)? max:a*b;
            }
        }
    }
    return max;
}

沒有留言:

張貼留言