给你一个字符串数组 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]
仅包含小写字母
class Solution:
def maxProduct(self, words: List[str]) -> int:
n = len(words)
mask = [0] * n
for i, word in enumerate(words):
for ch in word:
mask[i] |= 1 << (ord(ch) - ord('a'))
ans = 0
for i in range(n - 1):
for j in range(i + 1, n):
if mask[i] & mask[j] == 0:
ans = max(ans, len(words[i]) * len(words[j]))
return ans
class Solution {
public int maxProduct(String[] words) {
int n = words.length;
int[] masks = new int[n];
for (int i = 0; i < n; ++i) {
for (char c : words[i].toCharArray()) {
masks[i] |= (1 << (c - 'a'));
}
}
int ans = 0;
for (int i = 0; i < n - 1; ++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;
}
}
class Solution {
public:
int maxProduct(vector<string>& words) {
int n = words.size();
vector<int> mask(n);
for (int i = 0; i < n; ++i)
for (char ch : words[i])
mask[i] |= 1 << (ch - 'a');
int ans = 0;
for (int i = 0; i < n - 1; ++i)
for (int j = i + 1; j < n; ++j)
if (!(mask[i] & mask[j]))
ans = max(ans, (int)(words[i].size() * words[j].size()));
return ans;
}
};
func maxProduct(words []string) int {
n := len(words)
mask := make([]int, n)
for i, word := range words {
for _, c := range word {
mask[i] |= (1 << (c - 'a'))
}
}
ans := 0
for i := 0; i < n-1; i++ {
for j := i + 1; j < n; j++ {
if mask[i]&mask[j] == 0 {
ans = max(ans, len(words[i])*len(words[j]))
}
}
}
return ans
}
func max(a, b int) int {
if a > b {
return a
}
return b
}