Skip to content

Instantly share code, notes, and snippets.

@vrat28
Created May 28, 2021 01:09
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/b3336b6401ea690e63562cdcfb67eb3c to your computer and use it in GitHub Desktop.
Save vrat28/b3336b6401ea690e63562cdcfb67eb3c to your computer and use it in GitHub Desktop.
Maximum Product word lengths (Swift)
class Solution {
func maxProduct(_ words: [String]) -> Int {
var maxLength = 0
var bitMap = [Int:Int]()
for word in words{
let bitMask = getBitMask(word)
// Multiple words can have same bitmasks (a , aaaaaa).
// We need to keep the max length only
if let currentLength = bitMap[bitMask] {
bitMap[bitMask] = max(currentLength, word.count)
}
else{
bitMap[bitMask] = word.count
}
}
for i in bitMap.keys{
for j in bitMap.keys{
if i & j == 0 {
maxLength = max(maxLength, bitMap[i]!*bitMap[j]!)
}
}
}
return maxLength
}
func getBitMask(_ str:String) -> Int {
var bitMask = 0
for char in str{
let maskOffset = getAsciiOffset(char)
bitMask |= 1 << maskOffset
}
return bitMask
}
func getAsciiOffset(_ char:Character) -> Int{
return Int(char.asciiValue!) - 97
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment