Skip to content

Instantly share code, notes, and snippets.

@vrat28
Created May 28, 2021 01:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrat28/3ff75700bce86c7eabf4a1e7c28bc590 to your computer and use it in GitHub Desktop.
Save vrat28/3ff75700bce86c7eabf4a1e7c28bc590 to your computer and use it in GitHub Desktop.
Max Products Word Length (Java)
class Solution {
public int bitNumber(char ch){
return (int)ch - (int)'a';
}
public int maxProduct(String[] words) {
Map<Integer, Integer> hashmap = new HashMap();
int bitmask = 0, bitNum = 0;
for (String word : words) {
bitmask = 0;
for (char ch : word.toCharArray()) {
// add bit number bitNumber in bitmask
bitmask |= 1 << bitNumber(ch);
}
// there could be different words with the same bitmask
// ex. ab and aabb
hashmap.put(bitmask, Math.max(hashmap.getOrDefault(bitmask, 0), word.length()));
}
int maxProd = 0;
for (int x : hashmap.keySet())
for (int y : hashmap.keySet())
if ((x & y) == 0) maxProd = Math.max(maxProd, hashmap.get(x) * hashmap.get(y));
return maxProd;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment