zoukankan      html  css  js  c++  java
  • LeetCode-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.

    Analysis:

    The soultion is calcuated by doing a product of the length of
    each string to every other string. Anyhow the constraint given is
    that the two strings should not have any common character. This
    is taken care by creating a unique number for every string. Image
    a an 32 bit integer where 0 bit corresponds to 'a', 1st bit
    corresponds to 'b' and so on.
    	 * 
    Thus if two strings contain the same character when we do and
    "AND" the result will not be zero and we can ignore that case.

    Solution:
     1 public class Solution {
     2     public int maxProduct(String[] words) {
     3         if (words.length==0) return 0;
     4 
     5         int[] masks = new int[words.length];
     6         for (int i=0;i<words.length;i++){    
     7             int mask = 0;        
     8             for (int j=0;j<words[i].length();j++){
     9                 mask |= 1 << (words[i].charAt(j)-'a');
    10             }
    11             masks[i] = mask;
    12         }
    13 
    14         int res = 0;
    15         for (int i=0;i<words.length;i++)
    16             for (int j=0;j<words.length;j++)
    17                 if ((masks[i] & masks[j]) ==0){
    18                     res = Math.max(res,words[i].length()*words[j].length());
    19                 }
    20 
    21         return res;
    22     }
    23 }
     
  • 相关阅读:
    第 1 章 Java 设计模式介绍
    Java 随心笔记1
    在Editplus中配置java编译(javac)和运行(java)的方法
    RabbitMQ/JAVA 客户端连接测试
    CentOS上的RabbitMQ安装
    AMQP与RabbitMQ简介
    Mongodb学习教程汇总
    selenium+python之iframe学习笔记
    selenium 上传文件,非input标签,安装pyuserinput
    selenium+python之元素定位的八种方法
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5779930.html
Copyright © 2011-2022 走看看