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.

题目:意思是根据给出的字符串数组,算出最大的两个不相同字符串长度的乘积,两个字符串的每一个字符都是不一样的才能算不同

思路:第一反应无疑是对每一个字符串进行字符次数统计,形成一个map数组,而后找出完全不同字符串的,找出乘积最大的一对返回。这样显然是可以解决问题,但是毫无想法可言,看看提示说用bit运算,照着先人代码一番思考后,思路明了,大致是,对于一个字符串的每一个字符与'a'的相对差值,将其放入一个26位的二进制数n的相应的位置,例如b就放在n的左起第二位,,,依次我们可以得到每一个字符串的的一个int数字,进而得到一个关于字符串数组的int数组,根据两个int[i]&int[j] == 0,这两个数的二进制就是完全相反的,对应的字符串也是完全不同的,算出长度乘积,找出最大的


public int maxProduct(String[] words) {

  int len = words.length;
  int [] bWords = new int [len];
  for(int i = 0;i<len;i++){
    for(int j = 0;j<words[i].length();j++){
    bWords[i] |= 1 << (words[i].charAt(j) - 'a');
    }
  }

  int max = 0;
  for(int i = 0;i<len;i++){
    for(int j = i+1;j<len;j++){
      if((bWords[i] & bWords[j]) == 0){//特别注意& ,==两个运算符的优先级
      max = Math.max(words[i].length() * words[j].length(),max);
        }
    }
  }
  return max;
}

 

posted @ 2016-07-28 10:05  Roger's  阅读(144)  评论(0编辑  收藏  举报