Recursive Solution in Swift


  • 0
        if n == 0 {
            return ""
        }
        if n == 1 {
            return "1"
        }
        
        let predecessor = countAndSay(n - 1)
        
        var preChars = [Character](predecessor.characters)
        
        var count = 1
        var result = ""
        
        for index in  0 ..< preChars.count {
            if index == preChars.count - 1 {
                result.appendContentsOf("\(count)\(preChars[index])")
                continue
            }
            
            if preChars[index] == preChars[index + 1] {
                count += 1
            } else {
                result.appendContentsOf("\(count)\(preChars[index])")
                count = 1
            }
        }
        
        return result
    }
    

Log in to reply
 

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