Created
May 28, 2021 01:09
-
-
Save vrat28/b3336b6401ea690e63562cdcfb67eb3c to your computer and use it in GitHub Desktop.
Maximum Product word lengths (Swift)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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