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.
思路
我们需要找出字符串数组中,两个没有重复字符的字符串,并且它们的乘积要最大。
我们当然需要统计数组中每一个字符串,字母出现的次数。但是用什么方法来统计呢?如果用哈希表,空间复杂度可能会有点高,毕竟我们只有确定的26个字母。我选择利用alphabet[26]
,来存储字母次数的统计量。
其实还有更有技巧的方法,可以把字母统计量用位操作的方式存储在整数当中。利用移位运算给整数的相应位数赋上相应的值即可。
接下来,我们将数组里的数的对应长度,两两相乘;如果不满足题意,就不考虑这个乘积。
|
|