318. Maximum Product of Word Lengths

package LeetCode_318

import java.util.*

/**
 * 318. Maximum Product of Word Lengths
 * https://leetcode.com/problems/maximum-product-of-word-lengths/
 * Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters.
 * If no such two words exist, return 0.

Example 1:
Input: words = ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16
Explanation: The two words can be "abcw", "xtfn".

Example 2:
Input: words = ["a","ab","abc","d","cd","bcd","abcd"]
Output: 4
Explanation: The two words can be "ab", "cd".

Example 3:
Input: words = ["a","aa","aaa","aaaa"]
Output: 0
Explanation: No such pair of words.

Constraints:
1. 2 <= words.length <= 1000
2. 1 <= words[i].length <= 1000
3. words[i] consists only of lowercase English letters.
 * */
class Solution {
    /**
     * solution: use IntArray to store each word's mask of char, then compare by AND;
     * Time complexity:O(n^2), Space complexity:O(n)
     * Nice explanation:
     * https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/1212054/Java-beats-100-with-Explanation
     * */
    fun maxProduct(words: Array<String>): Int {
        if (words.isEmpty()) {
            return 0
        }
        val size = words.size
        val marks = IntArray(size)
        for (i in 0 until size) {
            for (c in words[i]) {
                /*
                *creating unique number for each string,
                * marks[i] is a 32 bit Int where 0 bit corresponds to 'a', 1 bit corresponds 'b' and so on,
                * for example 'abcw' is: 10000000000000000000111
                * */
                marks[i] = marks[i] or (1 shl (c - 'a'))
            }
        }
        var max = 0
        for (i in 0 until size) {
            for (j in i + 1 until size) {
                //The AND will be 0 if both the integers have no bits in common (i.e, no common characters in the corresponding Strings.)
                //is two string NOT contains same character when we do AND the result will be ZERO
                if (marks[i] and marks[j] == 0) {
                    max = Math.max(max, words[i].length * words[j].length)
                }
            }
        }
        return max
    }
}

 

posted @ 2021-07-31 17:06  johnny_zhao  阅读(33)  评论(0编辑  收藏  举报