Leetcode ☞ 318. Maximum Product of Word Lengths ☆

来源:互联网 发布:海马苹果助手for mac 编辑:程序博客网 时间:2024/06/11 01:18

318. Maximum Product of Word Lengths

My Submissions
Total Accepted: 13056 Total Submissions: 33493 Difficulty: Medium

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.



























我的AC(40ms,击败76%):

int maxProduct(char** words, int wordsSize) {    int* bitForm = (int*)calloc(wordsSize, sizeof(int));    int* lengths = (int*)calloc(wordsSize, sizeof(int));    int max = 0, ans;        for(int i = 0; i < wordsSize; i++){        char* c = words[i];                while(*c){            bitForm[i] |= 1 << (*c++ - 'a');            lengths[i]++;        }//算出第i个字符串的bit形式及其长度                for(int j = 0 ; j < i ; j++){            if ( (bitForm[i] & bitForm[j]) == 0){//(bitForm[i] & bitForm[j]) == 0 如果不加括号。就先运行==,再运行&。                ans = lengths[i] * lengths[j];                max = ans > max ? ans : max ;            }        }    }        free(bitForm);    free(lengths);    return max;}

分析:

1、把字符串转换成int型的01序列【只含有a~z这26个字母,26位是在int型范围内的】:在字母表中排第几,就在第几(低)位,如 “acd”==>“1101”。“或运算”,不论某字母出现几次,该位都会为1。

通过以上转换,判断两字符串是否含有相同字母 ==> 判断两个int型数的&结果是否不为0

2、该题依旧用到了这个小技巧(在前【时间顺序/AC更高】几题出现过多次):

char* c = words[i];
        while(*c){巴拉巴拉的操作}


3、运算符优先级(“==”比“&”要高):

http://baike.baidu.com/link?url=l2dYzwoSVqEWM7YbolOqQmHAVTTJkk8D6gVjzcV9JoQtkh_6DynS1j4YIEmJXcDP_6VIyg7m4azVDjY35TOvWq


0 0
原创粉丝点击