Swift solution


  • 0
    class Solution {
        func maxProduct(_ words: [String]) -> Int {
            var result = 0
            var bits = [Int](repeatElement(0, count: words.count))
            
            for i in 0..<words.count {
                let chars = Array(words[i].characters)
                var val = 0
                for j in 0..<chars.count {
                    val |= (1 << (String(chars[j]).asciiValue - "a".asciiValue))
                }
                bits[i] = val
            }
            for i in 0..<bits.count {
                for j in (i + 1)..<bits.count {
                    if bits[i] & bits[j] == 0 {
                        result = max(result, words[i].characters.count * words[j].characters.count)
                    }
                }
            }
            
            return result
        }
    }
    
    extension String {
        var asciiValue: Int {
            get {
                let value = self.unicodeScalars.filter{$0.isASCII}.first?.value ?? 0
                return Int(value) 
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.