1. 题目

2. 思路
(1) 位运算
- 比较两个字符串是否含有相同的字符,时间复杂度至少是O(m+n),由于题目给出了字符串只包含26个小写字母,因此,可以先利用int类型整数的26个二进制位存储每个字母是否出现过的状态。
- 当比较两个字符串是否含有相同字符时,只需将两个整数做与运算,若结果为0,则表示不含有相同字符,时间复杂度降低到了O(1)。
3. 代码
public class Test {
public static void main(String[] args) {
}
}
class Solution {
public int maxProduct(String[] words) {
int n = words.length;
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < words[i].length(); j++) {
nums[i] |= (1 << (words[i].charAt(j) - 'a'));
}
}
int res = 0;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if ((nums[i] & nums[j]) == 0) {
res = Math.max(res, words[i].length() * words[j].length());
}
}
}
return res;
}
}