给定一个字符串数组 words
,找到 length(word[i]) * length(word[j])
的最大值,并且这两个单词不含有公共字母。你可以认为每个单词只包含小写字母。如果不存在这样的两个单词,返回 0。
示例 1:
输入:["abcw","baz","foo","bar","xtfn","abcdef"]
输出:16 解释: 这两个单词为
"abcw", "xtfn"
。
示例 2:
输入:["a","ab","abc","d","cd","bcd","abcd"]
输出:4 解释:
这两个单词为"ab", "cd"
。
示例 3:
输入:["a","aa","aaa","aaaa"]
输出:0 解释: 不存在这样的两个单词。
class Solution:
def maxProduct(self, words: List[str]) -> int:
n = len(words)
masks = [0] * n
for i, word in enumerate(words):
for c in word:
masks[i] |= (1 << (ord(c) - ord('a')))
ans = 0
for i in range(n - 1):
for j in range(i + 1, n):
if (masks[i] & masks[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> masks(n);
for (int i = 0; i < n; ++i)
for (char c : words[i])
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 = max(ans, (int) (words[i].size() * words[j].size()));
return ans;
}
};
func maxProduct(words []string) int {
n := len(words)
masks := make([]int, n)
for i, word := range words {
for _, c := range word {
masks[i] |= (1 << (c - 'a'))
}
}
ans := 0
for i := 0; i < n-1; i++ {
for j := i + 1; j < n; j++ {
if (masks[i] & masks[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
}