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.

Tips:

其实,因为每个字母都是小写字母,所以我们可以用一个int[] masks的26位去保存每个单词所包含的字母的信息:因为我们不关心每个单词中各个字母出现的个数,只关心是否出现,所以可以用1表示出现,0表示未出现。这样的好处是,经过这样的预处理之后,当需要判断两个单词是否有相同字母时,做个与计算就知道结果了(是否为0)。这样,我们就得到了O(n*n)的解法。

在优化过的解法中,还按照word的长度给这些word排序,这样一旦找到最大值可以立刻停止。很快。而总复杂度是O(n*n),所以可以sort。第一个版本为优化过,第二个为普通,第三个为没有bit manipulate的版本

没有bit的tip:the core of this problem is to figure out a data structure that can store what letters a word has and make the comparison of whether two words has same letter easier. We can either store the info in an 26 array or with a 32-bit integer.

Code:

results matching ""

    No results matching ""