About the swift version TLE


  • 0
    D

    here is my code ,and it's O(n^2) solution ,but it's always TLE.

    func maxProduct(_ words: [String]) -> Int {

    var newArray:[UInt32] = Array()
    var i = 0
    for str in words {
        
        newArray.append(0)
        if let array = str.cString(using: String.Encoding.ascii) {
            for ch in array {
                if ch != 0 {
                    newArray[i] |= UInt32(1) << UInt32(ch - 97)
                }
            }
        }
        i += 1
    }
    
    var res = 0
    for i in 0..<words.count {
        for j in i+1..<words.count {
            if ((newArray[i] & newArray[j])) == 0 {
                let value = words[i].characters.count *  words[j].characters.count
                
                if value > res {
                    res = value
                }
            }
    
        }
    }
    
    return res
    

    }


  • 0
    F

    I had the same issue before. It was caused by calculating the length of each string multiple times in the second loop. Just pre-calculate and store the length of each string in an array and that works.


  • 0

    This was just fixed. Try submitting again and your swift solution should get Accepted now.


Log in to reply
 

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