318. Maximum Product of Word Lengths

来源:互联网 发布:淘宝全球购为什么便宜 编辑:程序博客网 时间:2024/05/19 09:38

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.

思路:本题最直观的想法肯定是一个字符串一个字符串的比较,但是自己心里肯定也清楚,肯定是TLE的。我们可以优化比较两个字符串是否有公共部分的方法,用一个bitmap[i]表示words[i]转化后的2进制值,比如abc对应的是111,如果两个words[i]一位都不一样的话,想与就为0,。根据上面的思路可以得到ac的代码。

代码如下(已通过leetcode)

public class Solution {
   public int maxProduct(String[] words) {
    int[] map=new int[words.length];
    //Arrays.fill(map, 1);
    for(int i=0;i<words.length;i++) {
    for(int j=0;j<words[i].length();j++) {
    map[i]=map[i]|(1<<words[i].charAt(j)-'a');
    }
    }
    int max=0;
    for(int i=words.length-1;i>=1;i--) {
    for(int j=i-1;j>=0;j--) {
    if((map[i]&map[j])==0) {
    max=Math.max(max, words[i].length()*words[j].length());
    }
    }
    }
    return max;
   }
  
}

0 0
原创粉丝点击