• 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
        }
    }
  • 相关阅读:
    java之扩展运算符
    error LNK2005: _DllMain@12 已经在 dllmain.obj 中定义
    MinGW
    Gcc/MinGW/Cygwin/Msys 分别是什么?
    开源项目:windows下使用MinGW+msys编译ffmpeg
    MinGW安装和使用基础教程
    基于UDP高性能传输协议UDT doc翻译(一)
    基于UDT connect连接通信以及文件传输--客户端
    基于UDT connect连接通信以及文件传输--服务端
    FreeSWITCH第三方库(其他)的简单介绍(三)
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/15084628.html
Copyright © 2020-2023  润新知