-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path0318.最大单词长度乘积.java
78 lines (74 loc) · 1.75 KB
/
0318.最大单词长度乘积.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
* @lc app=leetcode.cn id=318 lang=java
*
* [318] 最大单词长度乘积
*
* https://leetcode.cn/problems/maximum-product-of-word-lengths/description/
*
* algorithms
* Medium (72.44%)
* Likes: 442
* Dislikes: 0
* Total Accepted: 73.9K
* Total Submissions: 101.7K
* Testcase Example: '["abcw","baz","foo","bar","xtfn","abcdef"]'
*
* 给你一个字符串数组 words ,找出并返回 length(words[i]) * length(words[j])
* 的最大值,并且这两个单词不含有公共字母。如果不存在这样的两个单词,返回 0 。
*
*
*
* 示例 1:
*
*
* 输入:words = ["abcw","baz","foo","bar","xtfn","abcdef"]
* 输出:16
* 解释:这两个单词为 "abcw", "xtfn"。
*
* 示例 2:
*
*
* 输入:words = ["a","ab","abc","d","cd","bcd","abcd"]
* 输出:4
* 解释:这两个单词为 "ab", "cd"。
*
* 示例 3:
*
*
* 输入:words = ["a","aa","aaa","aaaa"]
* 输出:0
* 解释:不存在这样的两个单词。
*
*
*
*
* 提示:
*
*
* 2 <= words.length <= 1000
* 1 <= words[i].length <= 1000
* words[i] 仅包含小写字母
*
*
*/
// @lc code=start
class Solution {
public int maxProduct(String[] words) {
int n = words.length;
int[] masks = new int[n];
for (int i = 0; i < n; i++) {
String word = words[i];
for (int j = 0; j < word.length(); j++)
masks[i] |= 1 << (word.charAt(j) - 'a');
}
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if ((masks[i] & masks[j]) == 0)
ans = Math.max(ans, words[i].length() * words[j].length());
}
}
return ans;
}
}
// @lc code=end