318. Maximum Product of Word Lengths

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_25026989/article/details/89736534
  1. 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:

Input: [“abcw”,“baz”,“foo”,“bar”,“xtfn”,“abcdef”]
Output: 16
Explanation: The two words can be “abcw”, “xtfn”.
Example 2:

Input: [“a”,“ab”,“abc”,“d”,“cd”,“bcd”,“abcd”]
Output: 4
Explanation: The two words can be “ab”, “cd”.
Example 3:

Input: [“a”,“aa”,“aaa”,“aaaa”]
Output: 0
Explanation: No such pair of words.

思路

如果用HashMap,需要比较字符次数比较多,可以用标记位数组或者HashSet来表示两个字符串是否重合。

代码

class Solution {
    public int maxProduct(String[] words) {
        if (words == null || words.length == 0)
		    return 0;
        int len = words.length;
        int[] value = new int[len];
        
        for (int i = 0; i < len; i++) {
            String tmp = words[i];
            value[i] = 0;
            for (int j = 0; j < tmp.length(); j++) {
                value[i] |= 1 << (tmp.charAt(j) - 'a'); // 这里是把1往左移动 " ch - a" 位,标记0--25位上的1确定a---z是否出现,value数组就是标记数组
            }
        }
        
        int maxProduct = 0;
        for (int i = 0; i < len; i++)
            for (int j = i + 1; j < len; j++) {
                if ((value[i] & value[j]) == 0 
                            && (words[i].length() * words[j].length() > maxProduct))
                    maxProduct = words[i].length() * words[j].length();
            }
        return maxProduct;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_25026989/article/details/89736534
今日推荐