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.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-of-word-lengths
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
判断是否有不同数字时,可以采用bit来记录每一个位。再取&,如果有相同的,那么&的结果肯定不是0;
class Solution {
public int maxProduct(String[] words) {
int ans = 0;
for (int i = 0; i < words.length; i++) {
for (int j = i + 1; j < words.length; j++) {
if (isDiff(words[i], words[j])) {
ans = Math.max(ans, words[i].length() * words[j].length() );
}
}
}
return ans;
}
public boolean isDiff(String str1, String str2){
int num1 = 0;
int num2 = 0;
for (char a: str1.toCharArray()) {
num1 = num1 | 1 << (a - '0');
}
for (char a: str2.toCharArray()) {
num2 = num2 | 1 << (a - '0');
}
int and = num1 & num2;
return and == 0;
}
}
本文介绍了一种算法,用于解决给定字符串数组中寻找两个不包含相同字母的单词,以获得它们长度的最大乘积。通过使用位运算,该算法能够高效地检查两单词是否包含重复字符。
304

被折叠的 条评论
为什么被折叠?



