Swift edition: I got time exceed limit error


  • 0
    J
    func countAndSay(_ n: Int) -> String {
        
        
        var primary = "1"
        if n == 1 {
            return primary
        }
        
        for _ in 2...n {
            primary = countAndSayFromLast(primary)
        }
        return primary
    }
    
    func countAndSayFromLast(_ string: String) -> String {
    
        var result = ""
        var temp = string
        
        if temp.characters.count == 1 {
            let character =  temp.characters.first!
            result.append("1")
            result.append(character)
            return result
        }
        
        while temp.characters.count > 0 {
            
            let sIndex = temp.startIndex
    
            let character =  temp.characters.first!
            
            var count = 1
            for index in 1..<temp.characters.count {
                
                let numIndex = temp.characters.index(sIndex, offsetBy: index)
                if  temp.characters[numIndex] == character {
                    count += 1
                } else {
                    break
                }
            }
            let eIndex = temp.characters.index(sIndex, offsetBy: count)
            result.append("\(count)")
            result.append(character)
            temp.characters.removeSubrange(sIndex..<eIndex)
        }
        
        return result
        
    }```

Log in to reply
 

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