【LeetCode】318. Maximum Product of Word Lengths 最大单词长度乘积(Medium)(JAVA)
题目地址: https://leetcode.com/problems/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.
Constraints:
- 0 <= words.length <= 10^3
- 0 <= words[i].length <= 10^3
- words[i] consists only of lowercase English letters.
题目大意
给定一个字符串数组 words,找到 length(word[i]) * length(word[j]) 的最大值,并且这两个单词不含有公共字母。你可以认为每个单词只包含小写字母。如果不存在这样的两个单词,返回 0。
解题方法
- 这一题主要难点在于如何判断两个字符串不存在相同的字符:最简单的方法,就是遍历两个字符串所有字符然后判断是否有相同的字符存在
- 暴力遍历存在的问题是每次判断两个字符串是否存在相同的字符,两个字符串都会被遍历一遍,相当于字符串被无效的多遍了 N 次
- 优化就是能不能只遍历一遍字符串呢?可以把每个出现的字符,当做二进制中 1 出现在相应的位置,也就是 abce 变为 10111 (1 << (‘a’ - ‘a’) + 1 << (‘b’ - ‘a’) + 1 << (‘xx’ - ‘a’)) , 因为相应字符可能出现多次,所以用或运算。 因为只有 26 个小写字母,所有用 int 存即可
- 如何判断两个字符串不存在相同的字符?也就是 (a & b) == 0 ,即没有相同位置的 1,就代表没有相同的字符
class Solution {
public int maxProduct(String[] words) {
int max = 0;
int[] count = new int[words.length];
for (int i = 0; i < words.length; i++) {
for (int k = 0; k < words[i].length(); k++) {
int index = words[i].charAt(k) - 'a';
count[i] |= (1 << index);
}
}
for (int i = 0; i < words.length; i++) {
for (int j = i + 1; j < words.length; j++) {
if ((count[i] & count[j]) == 0) max = Math.max(max, words[i].length() * words[j].length());
}
}
return max;
}
}
执行耗时:8 ms,击败了99.45% 的Java用户
内存消耗:38.4 MB,击败了94.94% 的Java用户
![](https://i-blog.csdnimg.cn/blog_migrate/6c56d31f951aece27c5faae608dfac2e.jpeg)