ID | Title | Difficulty | |
---|---|---|---|
Loading... |
318. Maximum Product of Word Lengths
Medium
LeetCode
Array, String, Bit Manipulation
Problem
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.
Code
class Solution {
private int encode(String s) {
int res = 0;
for (char c : s.toCharArray()) {
res |= (1 << (c - 'a'));
}
return res;
}
public int maxProduct(String[] words) {
int[] encodes = new int[words.length];
for (int i = 0; i < words.length; i++){
encodes[i] = encode(words[i]);
}
int res = 0;
for(int i = 0; i < encodes.length; i++) {
for(int j = 0; j < encodes.length; j++){
if((encodes[i] & encodes[j]) == 0) {
res = Math.max(res, words[i].length() * words[j].length());
}
}
}
return res;
}
}
class Solution:
def maxProduct(self, words: List[str]) -> int:
encodes = [0] * len(words)
for i, word in enumerate(words):
enc = 0
for c in word:
enc |= 1 << (ord(c) - ord('a'))
encodes[i] = enc
res = 0
for i, word1 in enumerate(words):
for j, word2 in enumerate(words):
if encodes[i] & encodes[j] == 0:
res = max(res, len(word1) * len(word2))
return res
按 <- 键看上一题!
317. Shortest Distance from All Buildings
按 -> 键看下一题!
319. Bulb Switcher