zoukankan      html  css  js  c++  java
  • [LeetCode][JavaScript]Maximum Product of Word Lengths

    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.

     
     
     
     

     
     
     

    最直接的想法,两两比较,算出最大值。

    其中比较的操作要做n^2次,只能用效率高的位运算。

    先遍历一遍words,把单词转成二进制的数。

    a对应2的0次,b对应2的1次,以此类推。

    z y ... d c b a
    2^25 2^24 ... 4 2 1 0

    比较两个单词是不是包含重复字母的时候,只需要用&运算看结果是否为0。

     1 /**
     2  * @param {string[]} words
     3  * @return {number}
     4  */
     5 var maxProduct = function(words) {
     6     var i, j, max = 0;
     7     var bitDict = [];
     8     for(i = 0; i < words.length; i++)
     9         bitDict[i] = word2Num(i);
    10     for(i = 0; i < words.length; i++)
    11         for(j = 0; j < words.length; j++)
    12             if(i !== j && !hasSharedLetter(i, j))
    13                 max = Math.max(max, words[i].length * words[j].length);
    14     return max;
    15 
    16     function word2Num(index){
    17         var res = 0, charCodeA = 'a'.charCodeAt();
    18         for(var i = 0 ; i < words[index].length; i++)
    19             res |= Math.pow(2, words[index][i].charCodeAt() - charCodeA);
    20         return res;
    21     }
    22     function hasSharedLetter(index1, index2){
    23         if((bitDict[index1] & bitDict[index2]) === 0) return false;
    24         return true;
    25     }
    26 };
  • 相关阅读:
    自动化测试工具Gauge--contexts 与 Tear Down steps
    Redis官网第一次闲逛
    针对 《Linux就该这么学》 之 “第三章---管道符、重定向、环境变量” 摘抄、操练及拓展
    父shell 和 子shell; shell脚本的几种执行方式
    麒麟操作系统操练Linux基操
    HTTP代理
    gcc/g++ 安全编码
    golang 生成rsa秘钥对
    depth of feild
    Emission pass
  • 原文地址:https://www.cnblogs.com/Liok3187/p/5061408.html
Copyright © 2011-2022 走看看