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 @   johnny_zhao  阅读(37)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示